//
//  ViewController.m
//  AccuroFit
//
//  Created by Yongfeng Li on 8/6/15.
//  Copyright (c) 2015 Nci Technology Inc. All rights reserved.
//

#import <AudioToolbox/AudioServices.h>


#import "UIBodyProfileViewCtrl.h"
#import "UIChooseBleDev.h"

#import "ViewController.h"
#import "HeaRateViewCtrl.h"
#import "afMenu.h"


#import "N_DataGoals.h"
#import "N_WgtData.h"
#import "N_FatData.h"
#import "H_Rate.h"
#import "H_RateRng.h"
#import "H_RateItem.h"
#import "N_BdpData.h"
#import "P_Steps.h"
#import "N_GroupInfo.h"
#import "StatusBarColorManager.h"
//#define IP_PORT 8899

static short _nWgtUnit = 2;
static short _nLastWunit = 2;
static BOOL _bConnBleDev = NO;

//for sync
//static BOOL _bNewSyncMeas = YES;
static NSDate* _dtSyncStart = nil;
static NSDate* _dtLastSync = nil;

static BOOL _bSyncStepEnd = NO;
static int _nLastSyncSteps = 0;
static float _fLastSyncDists = 0.0;
static float _fLastSyncCalors = 0.0;

static NSTimer* _syncTimer = nil;
//static BOOL _bSyncException = NO;

@interface ViewController ()<HeaRateViewCtrlDelegate>

@property (nonatomic , strong) NSMutableArray *items;

@end

@implementation ViewController {
  UILabel* _lblMsg;
  UILabel* _deviceName;
  
  UIImageView* _ivDropdwon;
  NIDropDownList* _ddlUserList;
  UILabel* _lblDropDownList;
  NSUInteger _nMemberUserCount;
  
  UILabel* _lblHrateElaped;
  
  UIRingMeter* _ringMater;
  UIButton* _btnAdd;
  UIButton* _btnPlay;
    
    //UIImageView* _ivBkgdPage;
  UIImageView* _ivBkgdMid;
  UIBottView* _ivBottom;
  UIWgtMeasType* _wmtWgtType;

  NcitWiFiDev* _NcitWiFiDev;
  NcitBleDevice* _ncitBleDev;
    
  short _nMeasTypeIdx;
  short _nWgtTypeIdx;
    
  UIChooseBleDev* _cbdPedoDev;
  CBCharacteristic* _pBlePedoChar;
    
    //body Info
  NSInteger _nBodyId;
  NSString* _sTagId;
  
  NSString* _sBodyName;
  short _nAgeYear;
  float _fBodyWgt;
  float _fBodyHgt;
  short _nHgtMm;
  short _nSexNum;
  short _nExeLvl;
  
  short _nChestCm;
  short _nWaistCm;
    
  NSString* _sBodyHgt;
  //NSString* _UserCardNo;
  
  float _fBodyLastWgt;
  short _nBodyLastWu;
    
  //meas data
  BOOL _bFixBleUser;
    
  //pedostep
  int _nSteps;
  float _fDists;
  float _fCalors;
    
  NSMutableArray* _maLastData;
    
  BOOL _bSyncStepData;
  BOOL _bSyncStepDataEnd;
  
  UILabel* _lblPlusTips;
  UILabel* _lblPlayTips;
  
  BOOL _bFirstShow;
  //UIButton* _btnStopMeas;
  UIImageView* _imgCaloryView;
  UILabel* _lblCaloryVal;
  
  //hrate meas point
  NSInteger _nHrateId;
  H_Rate* _pHrate;
  NSDate* _dtHrmPoint;
  
  float _fRngLow;
  float _fRngUpp;
  //double _dElapsedTime;

  float _fCalry;
  CGFloat _pfDurHrate[6];
  //CGFloat _pfPointCoef[6];
  
  short nDurCount;
  double _dAvgHrate;
  CGFloat _fBatterylvl;
  
  NSInteger _nHrmRcvCount;
  NSDate* _dtMeas;
  NSDate* _dtLast;
  
  float _yMinLine;
  float _yMaxLine;
  
  BOOL _bUpdedWgtInfo;
  
  //get wifi data
  NSURLSession* _netSession;
  NSTimer* _wifiScaleTimer;
  
  UISwitch* _swFiFiScanCard;
  UILabel* _lblScanTips;
  Byte _nIosDevTypeIdx;
  
  UIButton* _btnDownShow;
  
  NSInteger _nLastBodyId;
  NSString* _sLastBodyName;
  
  BOOL _bIpad;
  
  NSMutableArray* _items;
  
  UIBodyProfileViewCtrl* _vcSetting;
  
  CGFloat _fScrWidth;
}

@synthesize items = _items;

@synthesize m_bSyncStepData = _bSyncStepData;
@synthesize m_bUpdedWgtInfo = _bUpdedWgtInfo;

- (void) getUserRegInfo
{
    self.view.backgroundColor = [UIColor whiteColor];
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  LoginBodyInfo* bodyInfo = pApp.m_bodyInfo;
  if(bodyInfo == nil)
    return;
    
  _nBodyId = bodyInfo.m_nBodyId;
  _sTagId = bodyInfo.m_sTagId;
  NSString* sFirstName = bodyInfo.sFirst;
  NSString* sLastName = bodyInfo.sLast;
  if(sFirstName.length > 0 || sLastName.length > 0)
    _sBodyName = [NSString stringWithFormat:@"%@ %@", sFirstName, sLastName];
  else
    _sBodyName = bodyInfo.sEmail;

  _nAgeYear = bodyInfo.nYearAge;
  _fBodyWgt = bodyInfo.fBodyWgt;
  if(bodyInfo.nWgtUn == 2)
    _fBodyWgt *= _LbtoKg;
    
  _fBodyHgt = bodyInfo.fBodyHgt;
  _nHgtMm = bodyInfo.nHgtMm;
  _nSexNum = bodyInfo.nGender;
  _nExeLvl = bodyInfo.nActLvl;
  //_UserCardNo = bodyInfo.m_sTagId;
  _nWgtUnit = bodyInfo.nWgtUn;
  _nLastWunit = _nWgtUnit;
    
    if(bodyInfo.nHgtUn == 2) {
      Byte nInch = (bodyInfo.fBodyHgt - (Byte)bodyInfo.fBodyHgt) * 12.0;
      _sBodyHgt = [NSString stringWithFormat:@"%i ft  %i in", (short)bodyInfo.fBodyHgt, nInch];
      _nChestCm = (short)(bodyInfo.fChestSize * _IntoCm + 0.5);
      _nWaistCm =  (short)(bodyInfo.fWaistLine * _IntoCm + 0.5);
    }
    else {
      _sBodyHgt = [NSString stringWithFormat:@"%.3fm", bodyInfo.fBodyHgt];
      _nChestCm = (short)bodyInfo.fChestSize;
      _nWaistCm = (short)bodyInfo.fWaistLine;
    }
  
}

- (void)viewDidLoad {
    [super viewDidLoad];
  _nChestCm = 0;
  _nWaistCm = 0;
  
  _nIosDevTypeIdx = 0;
    // Do any additional setup after loading the view, typically from a nib.
  //self.view.backgroundColor = [UIColor colorWithRed:0.528 green:0.128 blue:0.128 alpha:0.5];
  //self.view.backgroundColor = [UIColor colorWithWhite:0.175 alpha:0.50];
  
  /*CGRect rt = self.view.bounds;
  rt.size.height -= 20;
  UIGraphicsBeginImageContext(self.view.frame.size);
  [[UIImage imageNamed:@"ic-mainbkgd.png"] drawInRect:rt];
  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  self.view.backgroundColor = [UIColor colorWithPatternImage:image];*/
  self.view.backgroundColor = [UIColor colorWithWhite:0.175 alpha:0.50];
  
  //UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"ic-mainbkgd.png"]];
  //self.view.backgroundColor = background;
    
    //UIImage* iLeft = [[UIImage imageNamed:@"ic-list.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    UIImage* iRight = [self getImageScale:@"ic-list.png" scale: 0.4];
//    UIImage *rightImg = [UIImage imageNamed:@"ic-list.png"];
//    
//    UIButton *rBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    rBtn.frame = CGRectMake(0, 0, 25, 25);
//    [rBtn setImage:rightImg forState:UIControlStateNormal];
//    rBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
//    [rBtn addTarget:self action:@selector(selectLeftAction:) forControlEvents:UIControlEventTouchUpInside];
    
//    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithImage:rightImg style:UIBarButtonItemStylePlain
//                                                                   target:self action:@selector(selectLeftAction:)];
    //UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:rBtn];
    //self.navigationItem.rightBarButtonItem = rightButton;
    /*UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:nil action:nil];  
    self.navigationItem.backBarButtonItem = item;*/
  self.navigationItem.backBarButtonItem = nil;
        
  CGRect frame = [[UIScreen mainScreen] bounds];
  CGFloat W = frame.size.width;
  CGFloat H = frame.size.height;
  BOOL bIpad = H > 1000;
  _fScrWidth = W;
  _bIpad = bIpad;
  
  //AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  //UIImage* imgback = [pApp getImageScale:(_bIpad?@"ic-mainbkgd@1024.png":@"ic-mainbkgd.png") scale:(_bIpad?1.0:0.32)];
//  [self.view setBackgroundColor:[UIColor colorWithPatternImage:imgback]];
   
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:self.view.frame];
    imgView.contentMode = UIViewContentModeScaleAspectFill;
    imgView.image = [UIImage imageNamed:@"ic-mainbkgd"];
    [self.view insertSubview:imgView atIndex:0];
    
    //UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)];0
    //self.navigationItem.rightBarButtonItem = addButton;
    //self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];
  
  _nMeasTypeIdx = 0;
  _nWgtTypeIdx = 0;
  
  CGFloat yPos = (H > 1000)? 80.0f: 50.0f;
  [self initViewCtrls:yPos scrWdt:W scrHgt:H];
  
  
  //ble init
  [self initWiFiBleDev];
  
  [_ringMater setRingImage:_nMeasTypeIdx];
  [_ivBottom setMeasIdx:_nMeasTypeIdx];
    
  CGFloat yyPos = (H <= 480)? 65: 70;
  _lblMsg = [[UILabel alloc] initWithFrame:CGRectMake(20, yyPos + 6, W-40, 25)];
  _lblMsg.textColor = [UIColor grayColor];
  _lblMsg.font = [UIFont fontWithName:@"Calibri" size:24.0];
    _lblMsg.font = [UIFont systemFontOfSize:20];
  _lblMsg.backgroundColor = [UIColor clearColor];
  _lblMsg.textAlignment = NSTextAlignmentCenter;
  [self.view addSubview:_lblMsg];
  
    _deviceName = [[UILabel alloc] initWithFrame:CGRectMake(20, yyPos + 30, W-40, 20)];
    _deviceName.textColor = [UIColor colorWithRed:112.0/255 green:42.0/255 blue:135.0/255 alpha:0.75];
    _deviceName.font = Semibold(11);
    _deviceName.backgroundColor = [UIColor clearColor];
    _deviceName.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_deviceName];
    
    
  //member user
  CGFloat xxPos = W / (bIpad?4:6) - 8;
  CGFloat fWid = W / (bIpad?2: 1.5);
  CGFloat fHgt = bIpad?H*1/2: H-yPos-80;
  _ddlUserList = [[NIDropDownList alloc] initWithFrame:CGRectMake(xxPos, yyPos + 52, fWid, fHgt) type:98];
  _ddlUserList.delegate = self;
  
  UIImage* iDorpDown = [UIImage imageNamed:@"ic-dropdown.png"];
  _ivDropdwon = [[UIImageView alloc] initWithFrame:CGRectMake(xxPos, yyPos + 22, fWid, 30)];
  _ivDropdwon.image = iDorpDown;
  [self.view addSubview:_ivDropdwon];
  UITapGestureRecognizer *ivSingleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapDropDown)];
  ivSingleTap.numberOfTapsRequired = 1;
  [_ivDropdwon setUserInteractionEnabled:YES];
  [_ivDropdwon addGestureRecognizer:ivSingleTap];
  
  
  _lblDropDownList = [[UILabel alloc] initWithFrame:CGRectMake(xxPos+8, yyPos+25, fWid, 25)];
  _lblDropDownList.textColor = [UIColor grayColor];
  _lblDropDownList.font = [UIFont systemFontOfSize: 16.0];
  _lblDropDownList.backgroundColor = [UIColor clearColor];
  _lblDropDownList.textAlignment = NSTextAlignmentLeft;
  _lblDropDownList.text = @"    tap to choose user...";
  [self.view addSubview:_lblDropDownList];
  
  //[self setMemberUsersInfo];
  //member users
  
  //buttons text tips
  CGFloat fTipxPos = _btnAdd.frame.origin.x;
  CGFloat fTipyPos = _btnAdd.frame.origin.y;
  _lblPlusTips = [[UILabel alloc] initWithFrame:CGRectMake(fTipxPos-30, fTipyPos+40, 104, 25)];
  _lblPlusTips.textColor = [UIColor colorWithRed:112.0/255 green:42.0/255 blue:135.0/255 alpha:0.75];
  _lblPlusTips.font = [UIFont systemFontOfSize:13.0];
  _lblPlusTips.backgroundColor = [UIColor clearColor];
  _lblPlusTips.textAlignment = NSTextAlignmentCenter;
  _lblPlusTips.text = NSLocalizedString(@"History", nil);
  [self.view addSubview:_lblPlusTips];
  
  fTipxPos = _btnPlay.frame.origin.x;
  fTipyPos = _btnPlay.frame.origin.y;
  _lblPlayTips = [[UILabel alloc] initWithFrame:CGRectMake(fTipxPos-45, fTipyPos+40, 128, 25)];
  _lblPlayTips.textColor = [UIColor blackColor];
  _lblPlayTips.font = [UIFont systemFontOfSize:((H<481)?11.4:12.5)];
  _lblPlayTips.backgroundColor = [UIColor clearColor];
  _lblPlayTips.textAlignment = NSTextAlignmentCenter;
  if(_nMeasTypeIdx == 0) {
    _lblPlayTips.text = NSLocalizedString(@"Find HRM", nil);
    _lblPlayTips.textColor = [UIColor colorWithRed:112.0/255 green:42.0/255 blue:135.0/255 alpha:0.75];
  }
  else {
    _lblPlayTips.text = NSLocalizedString(@"Find Device", nil);
    _lblPlayTips.textColor = [UIColor colorWithRed:0.0/255 green:140.0/255 blue:189.0/255 alpha:0.75];
  }
  [self.view addSubview:_lblPlayTips];
    
    _cbdPedoDev = nil;
    
    //_UserCardNo = @"00060013";
    _nSteps = 0;
    _fDists = 0;
    _fCalors = 0;

    _bSyncStepData = NO;
    _bSyncStepDataEnd = NO;
    _pBlePedoChar = nil;
  
    _ringMater.txtDelegate = self;
  
  _bFirstShow = YES;
  _lblHrateElaped = nil;
  
  //_btnStopMeas = nil;
  _imgCaloryView = nil;
  _lblCaloryVal = nil;
  
  _nHrateId = 0;
  _pHrate = nil;
  _nHrmRcvCount = 0;
  _dtLast = nil;
  //for(int i=0; i<_nDurtBarNumber; i++) {
    //_pfPointCoef[i] = 1.0 + i;
  //}
  _dtHrmPoint = nil;
  _fCalry = 0.0;
  _dAvgHrate = 0;
  _fBatterylvl = 0.0;
  
  _fRngLow = 0.0;
  _fRngUpp = 0.0;
  
  [self setupSwipeGesture];
  
  //_nLastWunit = pApp.m_bodyInfo.nWgtUn;
  _nLastWunit = _nWgtUnit;
  _bUpdedWgtInfo = NO;
  
  //wifi scale data http
  NSURLSessionConfiguration* cnfgSession = [NSURLSessionConfiguration defaultSessionConfiguration];// [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier: @"HrateSync"];
  //cnfgSession.timeoutIntervalForRequest = 24.0;
  //cnfgSession.timeoutIntervalForResource = 24.0;
  _netSession = [NSURLSession sessionWithConfiguration:cnfgSession delegate: self delegateQueue: nil];
  _wifiScaleTimer = nil;
  
  yPos = H - 20;
  UIImage* iDown = [self getImageScale: @"ic-uarrow_sel.png" scale:1.0];
  _btnDownShow = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnDownShow.frame = CGRectMake((W-38)/2+3, yPos, 38, 14);
  [_btnDownShow setBackgroundImage:iDown forState:UIControlStateNormal];
  [_btnDownShow addTarget:self action:@selector(hideShowBotmCtrls:) forControlEvents:UIControlEventTouchUpInside];
//  [self.view addSubview:_btnDownShow];
  
  [self setupSwipeGestureDownUp];
  _btnDownShow.hidden = YES;
  
  [self.view addSubview:_ddlUserList];
  
  
  //family member just hide
  _ddlUserList.hidden = YES;
  _ivDropdwon.hidden = YES;
  _lblDropDownList.hidden = YES;
  //[self hideMemberUserCtrls:YES];
  
  _nLastBodyId = 0;
  _sLastBodyName = nil;
  
  _items = nil;
  _vcSetting = nil;
  
  self.navigationItem.leftBarButtonItem = nil;
  //self.navigationItem.sho
}

-(void)getDeviceName:(NSString *)deviceName {
    _deviceName.text = deviceName;
}

-(void)getDevice:(NSString *)deviceName {
    _deviceName.text = deviceName;
}

- (void) initViewCtrls:(CGFloat) yPos scrWdt:(CGFloat) W scrHgt:(CGFloat)H
{
  BOOL bIpad = H > 1000;
  BOOL bWider = W > 320;
  BOOL bIp4s = H <= 480;
  BOOL bPlus = !bIpad && H >= 736;
  if(bIpad)
    _nIosDevTypeIdx = 1;
  else if (bPlus)
    _nIosDevTypeIdx = 2;
  else if (bWider)
    _nIosDevTypeIdx = 3;
  else if(!bIp4s)
    _nIosDevTypeIdx = 4;
  else
    _nIosDevTypeIdx = 5;
    
    //ring meter y pos
    CGFloat yyPos = (H <= 480)? (yPos-18) : (yPos-20);
    yyPos += 20;
    if(bIpad)
        yyPos += 25;
    else if(bPlus)
        yyPos -= 15;
    
    //ring meter hgt
    CGFloat fHgt = H * 4.0 / 7.0;//W-130;
    
    //mid img bgkd
  //if(!bIpad) {
  //CGFloat fBackHgt =  H * 3.0/ 4.0 - 15 - yyPos - fHgt + (bIpad?20:bPlus?-8:(bWider?58:bIp4s?42:61));
  /*CGFloat fBackHgt =  H * 3.0/ 4.0 - 15 - yyPos - fHgt + (bIpad?20:bPlus?-8:(bWider?60:bIp4s?42:61));
    //if(bIpad)
        //fBackHgt += 100;
    UIImage* iBkgd = [[UIImage imageNamed:@"ic-mainbkgd.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    //_ivBkgdMid = [[UIImageView alloc] initWithFrame:CGRectMake(W/(bIpad?100:6.4), yyPos+fHgt-(bIpad?20:(bPlus?70:60)), W-(bIpad?10:(bWider?W/4.0:W/3.2)), fBackHgt+(bIpad?20:60))];
  _ivBkgdMid = [[UIImageView alloc] initWithFrame:CGRectMake(0, yyPos+fHgt-(bIpad?20:(bPlus?62:(bWider?59:bIp4s?46:60))), W, fBackHgt)];
    [_ivBkgdMid setImage:iBkgd];
    _ivBkgdMid.alpha = bIpad?0.520:0.520;
    //_ivBkgdMid.backgroundColor = [UIColor redColor];
    [self.view addSubview:_ivBkgdMid];*/
  //}
  
    //ring meter ctrl
  _ringMater = [[UIRingMeter alloc] initWithFrame:CGRectMake(bIpad?60:20, yyPos + (_bIpad?5:0), W-(bIpad?120:70), fHgt)];
  [self.view addSubview:_ringMater];
    
    //button
    CGFloat xPos = W - (bIpad? 100: 78);
    yyPos += fHgt / (bIpad?20.0:6.0);
    if(H <= 480) {
        xPos += 12;//10;
        yyPos -= 22;
    }
    UIImage* iBtn = [self getImageScale: @"ic-add.png" scale:(0.5)];
    _btnAdd = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _btnAdd.frame = CGRectMake(xPos+20, yyPos-40, 50, 50);
    [_btnAdd setBackgroundImage:iBtn forState:UIControlStateNormal];
    [_btnAdd addTarget:self action:@selector(tapImgBtnView:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnAdd];
  
    
    //play btn
    yyPos += fHgt - (bIpad?90:(bWider?176:160));
    if(bIpad)
        yyPos -= 5;
    else if (bIp4s)
         yyPos += 20;

    //iBtn = [self getImageScale: @"ic-play.png" scale:(1.0)];
  iBtn = [self getImageScale: @"btn-search.png" scale:(0.5)];
  _btnPlay = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnPlay.frame = CGRectMake(xPos+20, self.view.frame.size.height / 2, 50, 50);
  [_btnPlay setBackgroundImage:iBtn forState:UIControlStateNormal];
  [_btnPlay addTarget:self action:@selector(tapImgBtnView:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:_btnPlay];
  
  //_swFiFiScanCard = [[UISwitch alloc] initWithFrame:CGRectMake(W/3-(bIp4s?40:bIpad?30:48), yyPos + (bIp4s?65:bIpad?40:bPlus?48:55), 100, bIp4s?24:32)];
  //_swFiFiScanCard.onImage = [UIImage imageNamed:@"ic-update.png"];
  //_swFiFiScanCard.offImage = [UIImage imageNamed:@"ic-cancel.png"];
  //((UILabel *)[[[[[[_swFiFiScanCard subviews]lastObject]subviews]objectAtIndex:2] subviews] objectAtIndex:0]).text = @"Scan TagId WGT" ;
  //[_swFiFiScanCard addTarget:self action:@selector(onWiFiScanCard:) forControlEvents:UIControlEventTouchUpInside];
  //[self.view addSubview:_swFiFiScanCard];
  //_swFiFiScanCard.hidden = YES;
  
  _lblScanTips = [[UILabel alloc] initWithFrame:CGRectMake(W/3+(bIp4s?15:bIpad?25:7), yyPos + (bIp4s?65:bIpad?40:bPlus?48:55), 130, 32)];
  _lblScanTips.text = NSLocalizedString(@"Scan TagID Wgt", nil);
  _lblScanTips.font = [UIFont systemFontOfSize:bIp4s?12:bIpad?14:13];
  _lblScanTips.textAlignment = NSTextAlignmentLeft;
  _lblScanTips.textColor = [UIColor colorWithRed:112.0/255 green:42.0/255 blue:135.0/255 alpha:0.75];
  //_lblScanTips.backgroundColor = [UIColor redColor];
//  [self.view addSubview:_lblScanTips];
  _lblScanTips.hidden = YES;
  
    //bottom ctrl
    //yPos = yPos + W - (bIpad? 160 : 130);
    /*yyPos = yBottPos;
    if(fHgt < 0) {
        fHgt = 120;
    }
    else if(bIpad) {
        yyPos -=32;
    }
    else if(W <= 320) {
        yyPos += 14;
    }*/
    /*else if(W > 375 && W < 480) {
        yPos += 172;
    }*/
    
    
    
    yyPos = H * 3.0 / 4.0 - 45;
    if(bPlus)
        yyPos -= 70;
    fHgt = H - yyPos;
    _ivBottom = [[UIBottView alloc] initWithFrame:CGRectMake(0, yyPos, W, fHgt)];
    [self.view addSubview:_ivBottom];
    _ivBottom.bvDelegate = self;
    //_ivBottom.hidden = YES;
    
    _wmtWgtType = nil;
}

- (void) viewWillAppear:(BOOL)animated
{
  if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
  }

  [self calHrateMaxMinLine];
  
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if(![pApp isBodyLogged])
     return;
     
  [self getUserRegInfo];
  if(!_bUpdedWgtInfo) {
    [self setLastWgtMeasData:0.0f unit:0 fat:0.0f wat:0.0f];
    _bUpdedWgtInfo = YES;
  }
  
  if(_nMeasTypeIdx == 0 && !_bFirstShow)
    [self createHrmProcess];
  
    //reg user info
    //_lblMsg.text = [NSString stringWithFormat:@"Hello %@ (%i Y, %@)", _sBodyName, _nAgeYear, _sBodyHgt];

  //NSUInteger nHrtCount = 0;
  if(_nMeasTypeIdx < 3) {
    /*if(_nMeasTypeIdx == 0 &&  _ncitBleDev.bleDelegate == nil)
      [self setLastHrtMeasData:0];
    else */if(_nMeasTypeIdx == 1)
      [self setLastBdpMeasData:0 low:0];
    else if(_nMeasTypeIdx == 2)
      [self setLastStepMeasData:0];
    
    [_ivBottom setWgtMeasVal:pApp.m_bodyInfo.fBodyWgt unit:pApp.m_bodyInfo.nWgtUn];
    //return;
  }
  else {
    ;
  }
  
  
  //avg for all data
  /*if(nHrtCount > 1) {
    short nAvgHrate = [pApp loadHrateItemAvg:_nBodyId hRateId:0];
    [_ivBottom setHrtMeasVal:nAvgHrate];
  }*/
  
  short nHpres = 0, nLpres = 0;
  _maLastData = [NSMutableArray arrayWithArray:[pApp loadBdpData:_nBodyId from:nil to:nil sort:YES last:YES]];
  if(_maLastData != nil && _maLastData.count > 0) {
    N_BdpData* pBldp = [_maLastData objectAtIndex:0];
    nHpres = pBldp.bphVal.shortValue;
    nLpres = pBldp.bplVal.shortValue;
  }
  [_ivBottom setBdpMeasVal:nHpres low:nLpres];
  
  int nSteps = 0;
  _maLastData = [NSMutableArray arrayWithArray:[pApp loadStepsData:_nBodyId from:nil to:nil sort:NO last:YES]];
  if(_maLastData != nil && _maLastData.count > 0) {
    P_Steps* pStep = [_maLastData objectAtIndex:0];
    nSteps = pStep.nSteps.intValue;
  }
  [_ivBottom setStepMeasVal:nSteps];
  
  if(_nMeasTypeIdx == 0 && _bFirstShow) {
    [self onButtonTaps:_nMeasTypeIdx];
    [_btnAdd setBackgroundImage:[UIImage imageNamed:@"btn-hrate.png"] forState:UIControlStateNormal];
    _bFirstShow = NO;
  }
  else if(pApp.m_bClearCoreData) {
    _ncitBleDev.bleDelegate = nil;
    [self drawMeasRingMeter];
  }
  
  if(_bUpdedWgtInfo || (_nMeasTypeIdx == 3 && _nLastWunit != _nWgtUnit)) {
    [self setLastWgtMeasData:0.0f unit:0 fat:0.0f wat:0.0f];
    _nLastWunit = _nWgtUnit;
  }
  
  pApp.goalDelegate = self;
  NSString* sName = [NSString stringWithFormat:@"%@ %@", pApp.m_bodyInfo.sFirst, pApp.m_bodyInfo.sLast];
  dispatch_async(dispatch_get_main_queue(), ^{
//    _lblMsg.text = [NSString stringWithFormat:NSLocalizedString(@"Hello %@", nil), sName];
      
  });
  //AudioServicesPlaySystemSound(1115);
  _lblMsg.textColor =  _lblPlusTips.textColor;
    _deviceName.textColor = _lblPlusTips.textColor;
  [self getLastBodyInfo];
  //if(_nMemberUserCount  <= 1)
  [self setMemberUsersInfo];
  
  if(_nMeasTypeIdx == 0)
    [self setLastHrtMeasData:0];
  
  //special statusa bar
  
//  UIImage* iNav = [self getImageScale:@"ic-accuro-n.png" scale:0.75];
//    UIImage *img = [UIImage imageNamed:@"ic-accuro-n.png"];
//  UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
//    imgView.frame = CGRectMake(0, 0, 19, 19);
//  imgView.contentMode = UIViewContentModeScaleAspectFit;
//  self.navigationItem.titleView = imgView;
}

- (void) setupSwipeGesture
{
  //left swipe
  UISwipeGestureRecognizer * swipeGestureLeft = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGesture:)];
  swipeGestureLeft.direction = UISwipeGestureRecognizerDirectionLeft;
  [self.view addGestureRecognizer:swipeGestureLeft];
  //[swipeGestureLeft release];
  //right swipe
  /*UISwipeGestureRecognizer * swipeGestureRight = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGesture:)];
  swipeGestureRight.direction = UISwipeGestureRecognizerDirectionRight;
  [self.view addGestureRecognizer:swipeGestureRight];*/
  //[swipeGestureRight release];
}

- (void)handleSwipeGesture:(UIGestureRecognizer*)sender {
  //if(!_bConnBleDev)
    //return;
  
  //eWgtAppDelegate *appDelegate = (eWgtAppDelegate *)[[UIApplication sharedApplication] delegate];
  UISwipeGestureRecognizerDirection direction = [(UISwipeGestureRecognizer *)sender direction];
  
  bool bToLeft = direction == UISwipeGestureRecognizerDirectionLeft;
  //if(direction == UISwipeGestureRecognizerDirectionRight) {
    //_lblMsg.text = @"Right";
  //}
  
  
  CATransition* animation = [CATransition animation];
  [animation setDuration:0.5f];
  [animation setType:kCATransitionReveal];//(bToRight? kCATransitionMoveIn: kCATransitionReveal)];
  
  //[animation setSubtype:(bToRight?kCATransitionFromLeft:kCATransitionFromBottom)];
  [animation setSubtype:(bToLeft?kCATransitionFromRight:kCATransitionFromLeft)];
  //[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];//kCAMediaTimingFunctionEaseInEaseOut]];
  [[self.view.superview layer]addAnimation:animation forKey:@"switchHrateView"];
  
  if(bToLeft) {
    [self tapImgBtnView:nil];//]_btnPlay];
  }
}

- (void) setMemberUsersInfo {

  //_lblMsg.text = @"dwon tap";
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSArray* pUsers = [pApp loadMemberUserInfo:0 grpId:pApp.m_nLoginBodyId];
  if(pUsers == nil)
    return;
  
  NSMutableDictionary *dirDevMember = [[NSMutableDictionary alloc] init];
  NSUInteger nCount = pUsers.count;
  for(NSUInteger i=0; i<nCount; i++) {
    N_GroupInfo* pInfo = [pUsers objectAtIndex:i];
    if(pInfo == nil)
      continue;
    
    NSString* sName = pInfo.bodyEmail;
    NSString* sBodyId = [NSString stringWithFormat:@"%ld", (long)(pInfo.bodyId.integerValue)];
    [dirDevMember setValue: sName forKey:sBodyId];
  }
  NSString* sBodyName = pApp.m_sLoginEmail;
  NSString* sLogBodyId = [NSString stringWithFormat:@"%ld", (long)pApp.m_nLoginBodyId];
  [dirDevMember setValue: sBodyName forKey:sLogBodyId];

  NSString* sCurtBodyName = [NSString stringWithFormat:@"%@ %@", pApp.m_bodyInfo.sFirst, pApp.m_bodyInfo.sLast];
  NSString* sCurtBodyId = [NSString stringWithFormat:@"%ld", (long)pApp.m_bodyInfo.m_nBodyId];
 
  /*if(_nLastBodyId != 0)
    sCurtBodyId = [NSString stringWithFormat:@"%ld", (long)_nLastBodyId];
  if(_sLastBodyName != nil)
    sCurtBodyName = _sLastBodyName;
   else */
  if(pApp.m_nLoginBodyId == pApp.m_bodyInfo.m_nBodyId) {
    sCurtBodyName = pApp.m_sLastBodyName;
    _lblDropDownList.text = pApp.m_bodyInfo.sEmail;
    //pApp.m_bodyInfo.sFirst = sBodyName;
    //pApp.m_bodyInfo.sLast = @"";
    //[pApp getUserGoalData:YES];
  }
  else {
     _lblDropDownList.text = sCurtBodyName;
  }
  [_ddlUserList setListData:dirDevMember curSel:sCurtBodyId];

  if(_nLastBodyId != 0)
    _lblMsg.text = sCurtBodyName;
  
  
  _nMemberUserCount = nCount + 1;
}

- (void) getLastBodyInfo {
   AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if(pApp.m_nLastBodyId == 0)
    return ;
  
  _nLastBodyId = pApp.m_nLastBodyId;
  //_sLastBodyName = pApp.m_sLastBodyName;
  
  //pApp.m_bodyInfo.m_nBodyId = _nLastBodyId;
  /*NSRange rng = [_sLastBodyName rangeOfString:@" "];
  if(rng.location != NSNotFound) {
    pApp.m_bodyInfo.sFirst = [_sLastBodyName substringWithRange: NSMakeRange(0, rng.location)];
    pApp.m_bodyInfo.sLast = [_sLastBodyName substringFromIndex:rng.location+1];
  }
  _lblMsg.text = _sLastBodyName;*/
}

- (void) onTapDropDown
{
  if([_ddlUserList isPopup]) {
    [_ddlUserList hideDropDownList];
    _lblMsg.text = NSLocalizedString(@"Cancel", nil);
  }
  else {
    [_ddlUserList popupDropDownList];
  }
  
}

- (NSString *) niDropDownDelegateMethod: (NIDropDownList *) sender;
{
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
  NSString* sUserId = sender.sSelValId;
  NSString* sText = sender.sSelText;
  
  _nBodyId = sUserId.integerValue;
  _nLastBodyId = _nBodyId;
  [pApp resetBodyId:_nBodyId];
  
  [sender hideDropDownList];
  
  if(_nMeasTypeIdx == 0)
    [self setLastHrtMeasData:0];
  else if(_nMeasTypeIdx == 1)
    [self setLastBdpMeasData:0 low:0];
  else if(_nMeasTypeIdx == 2)
    [self setLastStepMeasData:0];
  else
    [self setLastWgtMeasData:0.0f unit:0 fat:0.0f wat:0.0f];
  
  /*pApp.m_bodyInfo.m_nBodyId = _nBodyId;
  NSRange rng = [sText rangeOfString:@" "];
  if(rng.location != NSNotFound) {
    pApp.m_bodyInfo.sFirst = [sText substringWithRange: NSMakeRange(0, rng.location)];
    pApp.m_bodyInfo.sLast = [sText substringFromIndex:rng.location+1];
  }*/
  
  [_ivBottom setWgtMeasVal:pApp.m_bodyInfo.fBodyWgt unit:pApp.m_bodyInfo.nWgtUn];
  
  _lblDropDownList.text = [NSString stringWithFormat:@"  %@", sText];
  if(pApp.m_nLoginBodyId != _nBodyId)
    _lblMsg.text = _lblDropDownList.text;
  
  return sUserId;
}

- (void) setMsgTitle:(NSString *)sTitle
{
  _lblMsg.text = sTitle; //[NSString stringWithFormat:@"Hello %@ %@", pApp.m_bodyInfo.sFirst, pApp.m_bodyInfo.sLast];
}

- (void) hideMemberUserCtrls:(BOOL)bHide
{
  _lblDropDownList.hidden = bHide;
  _ivDropdwon.hidden = bHide;
  _ddlUserList.hidden = bHide;
  
  if(!bHide) {
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    _nBodyId = pApp.m_nLoginBodyId;
    _lblDropDownList.text = pApp.m_bodyInfo.sEmail;
    _nBodyId = pApp.m_nLoginBodyId;
  }
}


- (IBAction)showMenuFromNavigationBarItem:(id)sender {
  
  // 通过NavigationBarItem显示Menu
//  if (sender == self.navigationItem.rightBarButtonItem) {
    //[afMenu setTintColor:[UIColor colorWithRed:0.118 green:0.573 blue:0.820 alpha:1]];
    [afMenu setTintColor:[UIColor colorWithRed:0.375 green:0.375 blue:0.375 alpha:1]];
    if ([afMenu isShow]){
      [afMenu dismissMenu];
    }
    else {
      [afMenu showMenuInView:self.view fromRect:CGRectMake(_fScrWidth-70, 63, 50, 0) menuItems:self.items selected:^(NSInteger index, afMenuItem *item) {
        NSLog(@"%@",item);
      }];
    }
//  }
  
  /*UIButton *btn = sender;
  CGRect rt = btn.frame;
  [afMenu showMenuInView:self.view fromRect:btn.frame menuItems:self.items selected:^(NSInteger index, afMenuItem *item) {
    NSLog(@"%@",item);
  }];*/
}

- (NSMutableArray *)items {
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  LoginBodyInfo* bodyInfo = pApp.m_bodyInfo;
  Byte nGender = bodyInfo.nGender;
  
  if (!_items) {
    // set title
    //afMenuItem *menuTitle = [afMenuItem menuTitle:@"Person Info" WithIcon:nil];
    UIImage* iCon = [self getImageScale:(nGender==1)?@"ic_male.png":@"ic_female" scale:1.32f];//[UIImage imageNamed:(nGender==1)?@"ic_male.png":@"ic_female"];
    afMenuItem *infoItem = [afMenuItem menuItem:@"Profile" image:iCon target:self action:@selector(personInfo:)];
    infoItem.foreColor = [UIColor whiteColor];
    infoItem.alignment = NSTextAlignmentLeft;
    infoItem.titleFont = [UIFont boldSystemFontOfSize:15.0f];
    
    iCon = [self getImageScale:@"ic-users.png" scale:1.20f];;//[UIImage imageNamed:@"ic_setting.png"];
    afMenuItem *userItem = [afMenuItem menuItem:@"Member" image:iCon target:self action:@selector(usersInfo:)];
    userItem.foreColor = [UIColor whiteColor];
    userItem.alignment = NSTextAlignmentLeft;
    infoItem.titleFont = [UIFont boldSystemFontOfSize:15.0f];
    
    iCon = [self getImageScale:@"ic_setting.png" scale:1.20f];;//[UIImage imageNamed:@"ic_setting.png"];
    afMenuItem *setItem = [afMenuItem menuItem:@"Setting" image:iCon target:self action:@selector(routerSettingInfo:)];
    setItem.foreColor = [UIColor whiteColor];
    setItem.alignment = NSTextAlignmentLeft;
    infoItem.titleFont = [UIFont boldSystemFontOfSize:15.0f];
    
    //set logout button
//    iCon = [UIImage imageNamed:@"ic_logout.png"];
     iCon =  [self getImageScale:@"ic_logout.png" scale:0.7f];
    afMenuItem *logoutItem = [afMenuItem menuItem:NSLocalizedString(@"Logout", nil) image:iCon target:self action:@selector(userLogout:)];
    logoutItem.foreColor = [UIColor whiteColor];
    logoutItem.alignment = NSTextAlignmentLeft;
    infoItem.titleFont = [UIFont boldSystemFontOfSize:15.0f];
    
    //set item
    _items = [@[infoItem,
                /*userItem,
                setItem,*/
                logoutItem] mutableCopy];
  }
  else {
    afMenuItem* info = [_items objectAtIndex:0];
    info.image = [self getImageScale:(nGender==1)?@"ic_male.png":@"ic_female" scale:1.32f];
    
  }
  return _items;
}

- (void) personInfo:(id)sender
{
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  UIStoryboard* mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
  UIBodyProfileViewCtrl* vcBodyProf = [mainStory instantiateViewControllerWithIdentifier:@"bodyProfViewCtrl"];
  [pApp.m_pNavController pushViewController:vcBodyProf animated:YES];
}

- (void) usersInfo:(id)sender
{
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  UIStoryboard* mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
  UIBodyProfileViewCtrl* vcFamiliMemb = [mainStory instantiateViewControllerWithIdentifier:@"memberViewCtrl"];
  [pApp.m_pNavController pushViewController:vcFamiliMemb animated:YES];
  
}

- (void) routerSettingInfo:(id)sender
{
  //_lblMsg.text = @"WiFi router setting in developing...";
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  UIStoryboard* mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
  if(_vcSetting == nil)
    _vcSetting = [mainStory instantiateViewControllerWithIdentifier:@"settingViewCtrl"];

  [pApp.m_pNavController pushViewController:_vcSetting animated:YES];
}

- (void) userLogout:(id)sender
{

  BOOL bIos8 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0;
  if(bIos8) {
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* logoutAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Logout", nil) style:UIAlertActionStyleDestructive
                                                         handler:^(UIAlertAction * action) {
                                                           AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                                                           pApp.m_nLastHrate = 0;
                                                           pApp.m_nCurtAvgHrt = 0;
                                                           
                                                           [pApp userLogout];
                                                         }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * action) {
                                                           _lblMsg.text = NSLocalizedString(@"Cancel", nil);
                                                         }];
    
    [alert addAction:logoutAction];
    [alert addAction:cancelAction];
    
    [self presentViewController:alert animated:YES completion:nil];
  }
  else {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Logout comfirm" message:@"Are you sure to logout!" delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Logout", nil), nil];
    [alertView show];
  }
}

- (void)setItems:(NSMutableArray *)items {
  _items = self.items;
}

- (void) calHrateMaxMinLine
{
  /*short nMaxHrt = 210 - _nAgeYear / 2 - _fBodyWgt * 0.05;
  float fMinVal = nMaxHrt * _FitHR_RngMin;
  float fMaxVal = nMaxHrt * _FitHR_RngMax;

  float fDelta = (fMaxVal - fMinVal) / 2;
  _yMinLine = fMinVal - fDelta;
  _yMaxLine = fMinVal + fDelta * 4;*/
  
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  short nMaxHrt = [pApp calHrateFitnessRng: NO];
  if(pApp.m_bodyInfo.nMaxBpm != nMaxHrt) {
    _yMaxLine =(float)pApp.m_bodyInfo.nMaxBpm;
  }
  else {
    _yMaxLine = (float)nMaxHrt;
  }
}


- (void) setupSwipeGestureDownUp
{
  //left swipe
  UISwipeGestureRecognizer* swipeGestureUp= [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGestureDownup:)];
  swipeGestureUp.direction = UISwipeGestureRecognizerDirectionUp;// || UISwipeGestureRecognizerDirectionDown®;
  //swipeGestureMove.numberOfTapsRequired = 1; //点击次数
  //swipeGestureMove.numberOfTouchesRequired = 1; //点击手指数
  [self.view addGestureRecognizer:swipeGestureUp];
  
  UISwipeGestureRecognizer* swipeGestureDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGestureDownup:)];
  swipeGestureDown.direction = UISwipeGestureRecognizerDirectionDown; //默认向右
  [self.view addGestureRecognizer:swipeGestureDown];
}

- (void)handleSwipeGestureDownup:(UIGestureRecognizer*)sender {
  //if(!_bConnBleDev)
  //return;
  
  //eWgtAppDelegate *appDelegate = (eWgtAppDelegate *)[[UIApplication sharedApplication] delegate];
  UISwipeGestureRecognizerDirection direction = [(UISwipeGestureRecognizer *)sender direction];
  
  //bool bToUp = direction == UISwipeGestureRecognizerDirectionUp;
  bool bToDown = direction == UISwipeGestureRecognizerDirectionDown;
  
  CATransition* animation = [CATransition animation];
  [animation setDuration:0.5f];
  [animation setType:kCATransitionReveal];
  
  
  [animation setSubtype:(bToDown?kCATransitionFade:kCATransitionMoveIn)];
  [[self.view.superview layer]addAnimation:animation forKey:@"switchHrateBot"];
  
  BOOL bHide = bToDown;
  UIImage* iArrow = [UIImage imageNamed:bHide?@"ic-uarrow_sel.png":@"ic-darrow_sel.png"];
  [_btnDownShow setBackgroundImage:iArrow forState:UIControlStateNormal];
//  [self hideShowBottomCtrls:bHide];
}

- (void) hideShowBotmCtrls:(id)sender
{
//  BOOL bHide = !_ivBottom.hidden;
//  [self hideShowBottomCtrls: bHide];
}

- (void) hideShowBottomCtrls:(BOOL)bHide
{

  UIImage* iShow = [UIImage imageNamed:bHide?@"ic-uarrow_sel.png":@"ic-darrow_sel.png"];
  [_btnDownShow setBackgroundImage:iShow forState:UIControlStateNormal];
  //_btnDownShow.hidden = YES;
  _ivBottom.hidden = NO;
  //return;

}

- (void) storeHrmMeasPoint:(NSInteger)nHrateId hrate:(H_Rate*)pHrate dtStart:(NSDate*)dtPoint calry:(CGFloat)fCalry dur:(CGFloat*)pfDurHrate avg:(short)nAvgHrate size:(short)nCount blvl:(CGFloat)fBlvl
{
  _nHrateId = nHrateId;
  _pHrate = pHrate;
  _dtHrmPoint = [dtPoint dateByAddingTimeInterval:0.0];
  _dtLast = [NSDate date];
  //_fPoints = fPoints;
  _fCalry = fCalry;
  _dAvgHrate = nAvgHrate;
  _fBatterylvl = fBlvl;
  
  nDurCount = nCount;
  double dElapsed = [[NSDate date] timeIntervalSinceDate:_dtHrmPoint];
  for(short i=0; i<nCount; i++) {
    _pfDurHrate[i] = pfDurHrate[i];
    //dElapsed += _pfDurHrate[i];
  }
  //_dElapsedTime = dElapsed;
  
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  pApp.m_pHrate = pHrate;
  pApp.m_nHrateId = nHrateId;
  
  _lblHrateElaped.hidden = NO;
  _lblHrateElaped.text = [pApp getHourMinSec:dElapsed];
  
  BOOL bHide = _ncitBleDev.bConnBleDev;
  _ivBottom.hidden = NO;
  _btnDownShow.hidden = !bHide;
  
  //
  short nMaxHrt = [pApp calHrateFitnessRng: NO];
  //if(pApp.m_bodyInfo.nMaxBpm != nMaxHrt)
  //nMaxHrt = pApp.m_bodyInfo.nMaxBpm;
  
  _fRngLow = nMaxHrt * 0.5;
  _fRngUpp = nMaxHrt * 0.7;
}

- (void) createHrmProcess
{
  UIImage* iBtn = nil;
  if(_ncitBleDev.bConnBleDev) {
  //if( YES) {
    _nHrmRcvCount = 0;
    _ncitBleDev.bleDelegate = self;
    //if(_btnStopMeas == nil && _lblHrateElaped == nil) {
    if(_imgCaloryView == nil & _lblHrateElaped == nil) {
      CGRect frame = [[UIScreen mainScreen] bounds];
      CGFloat W = frame.size.width;
      
      CGRect rt = _btnAdd.frame;
      CGFloat xPos = 80;
      _lblHrateElaped = [[UILabel alloc] initWithFrame:CGRectMake(xPos, rt.origin.y + (_bIpad?20:10), W-xPos*2, 30)];
      _lblHrateElaped.textColor = [UIColor colorWithRed:112.0/255 green:42.0/255 blue:135.0/255 alpha:0.75];
      _lblHrateElaped.font = [UIFont boldSystemFontOfSize:32.0];
      _lblHrateElaped.backgroundColor = [UIColor clearColor];
      _lblHrateElaped.textAlignment = NSTextAlignmentCenter;
//      [self.view addSubview:_lblHrateElaped];
      //_lblHrateElaped.text = @"Time: 9:12:34";
      
      
      rt.origin.x = (_nIosDevTypeIdx==1)?30:10;
      rt.origin.y += (_nIosDevTypeIdx==1)?152:82;
      rt.size.width = frame.size.height / 14 + (5-_nIosDevTypeIdx) * 16;
      if(_nIosDevTypeIdx == 1)
        rt.size.width *= 1.5;
      rt.size.height = rt.size.width;
      //CGFloat yPos = 144.1;
      //calory ring
      iBtn = [self getImageScale: NSLocalizedString(@"ring-calories", nil) scale:(1.0)];
      _imgCaloryView = [[UIImageView alloc] initWithImage:iBtn];
      _imgCaloryView.frame = rt;
      [self.view addSubview:_imgCaloryView];
      
      rt.origin.x += -2 + (5-_nIosDevTypeIdx) * 6;
      rt.origin.y += 22 + (5-_nIosDevTypeIdx) * 6;
      if(_nIosDevTypeIdx == 1) {
        rt.origin.x += 48;
        rt.origin.y += 50;
      }
      rt.size.width = 90;
      rt.size.height = 28;

      _lblCaloryVal = [[UILabel alloc] initWithFrame:rt];
      _lblCaloryVal.textColor = [UIColor colorWithRed:112.0/255 green:42.0/255 blue:135.0/255 alpha:1.0];
//      _lblCaloryVal.backgroundColor = [UIColor grayColor];
      _lblCaloryVal.textAlignment = NSTextAlignmentCenter;
      _lblCaloryVal.font = Semibold(frame.size.height / 23.5);
        _lblCaloryVal.center = _imgCaloryView.center;
      _lblCaloryVal.text = @"---";
      [self.view addSubview:_lblCaloryVal];
      
      /*iBtn = [self getImageScale: @"ic-stop.png" scale:(1.0)];
      _btnStopMeas = [UIButton buttonWithType:UIButtonTypeRoundedRect];
      _btnStopMeas.frame = rt; //CGRectMake(xPos, yPos, 64, 64);
      [_btnStopMeas setBackgroundImage:iBtn forState:UIControlStateNormal];
      [_btnStopMeas addTarget:self action:@selector(tapImgBtnView:) forControlEvents:UIControlEventTouchUpInside];
      [self.view addSubview:_btnStopMeas];*/
    }
    _imgCaloryView.hidden = NO;
    _lblCaloryVal.hidden = NO;
    //_btnStopMeas.hidden = NO;
    
    iBtn = [UIImage imageNamed:@"btn-stop.png"];
    _lblPlayTips.text = @"STOP";
  }
  else {
    _lblHrateElaped.hidden = YES;
    _imgCaloryView.hidden = YES;
    _lblCaloryVal.hidden = YES;
    _ncitBleDev.bleDelegate = nil;
    //if(_btnStopMeas)
      //_btnStopMeas.hidden = YES;
    iBtn = [UIImage imageNamed:@"btn-search.png"];
    
    if(_nMeasTypeIdx == 0)
      _lblPlayTips.text = NSLocalizedString(@"Find HRM", nil);
    else if(_nMeasTypeIdx == 1)
      _lblPlayTips.text = @"Find BP";
    else if(_nMeasTypeIdx == 2)
      _lblPlayTips.text = NSLocalizedString(@"Find Device", nil);
    else if(_nMeasTypeIdx == 3)
      _lblPlayTips.text = NSLocalizedString(@"Find Device", nil);
  }
  
  [_btnPlay setBackgroundImage:iBtn forState:UIControlStateNormal];
}

- (void) ProcrHrmStopMeas
{
  [_ncitBleDev stopMeas];
  if(_nHrateId != 0) {
     AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if(_pHrate != nil) {
      [pApp updHrateStartEndTime:_pHrate startTime:nil endTime:_dtMeas toSvr:YES];
      [self storeRateRngData:YES];
      pApp.m_nHrateId = 0;
    }
  }
  _imgCaloryView.hidden = YES;
  _lblCaloryVal.hidden = YES;
  
  _ivBottom.hidden = NO;
  _btnDownShow.hidden = YES;
}

- (void) viewWillDisappear:(BOOL)animated
{
    if(_nMeasTypeIdx == 2 && _nSteps > 0) {
        AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [pApp insertStepsData:pApp.m_bodyInfo.m_nBodyId step:_nSteps dist:_fDists calory:_fCalors date:[NSDate date] add:NO toSvr:YES];
        _nSteps = -1;
    }
}
/*-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}*/

-(void) updateUserInfo:(NSString *)sName age:(short)nAge hgt:(NSString *)sHgt
{
    _sBodyName = sName;
    _nAgeYear = nAge; 
    _sBodyHgt = sHgt;
    
    //_lblMsg.text = [NSString stringWithFormat:@"Hello %@ (%i Y, %@)", _sBodyName, _nAgeYear, _sBodyHgt];
//  _lblMsg.text = [NSString stringWithFormat:NSLocalizedString(@"Hello %@", nil), _sBodyName];
}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
  _lblMsg.text = NSLocalizedString(@"No enough memory!", nil);
  AudioServicesPlaySystemSound(1112);
}

- (void) setLastWgtMeasData:(float)fWgt unit:(short)nWu fat:(float)fFat wat:(float)fWat
{
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    //goal

  float fLwgt = 0, fLfat = 0, fLwat = 0;
  short nUnit = 2;
  if(fWgt > 0) {
    fLwgt = fWgt;
    nUnit = nWu;
    fLfat = fFat;
    fLwat = fWat;
  }
  else {
    //wgt
    _maLastData = [NSMutableArray arrayWithArray:[pApp loadWgtData:_nBodyId from:nil to:nil sort:NO last:YES]];
    if(_maLastData != nil && _maLastData.count > 0) {
      N_WgtData* pWgt = (N_WgtData*)[_maLastData objectAtIndex:0];
      if (pWgt != nil && pWgt.mWgtData != nil) {
        fLwgt = [pWgt.mWgtData floatValue];
        nUnit = [pWgt.mWgtUnit shortValue];
      }
    }

      //fat, wat
    _maLastData = [NSMutableArray arrayWithArray:[pApp loadFatData:_nBodyId from:nil to:nil sort:NO last:YES]];
    if(_maLastData != nil && _maLastData.count > 0) {
      N_FatData* pFat = (N_FatData*)[_maLastData objectAtIndex:0];
      if (pFat != nil && pFat.fatVal != nil) {
        fLfat = pFat.fatVal.floatValue;
        fLwat = pFat.watVal.floatValue;
      }
    }
  }
  
  _fBodyLastWgt = fLwgt;
  _nBodyLastWu = nUnit;
  
  //adjust va;
  //fLwgt += 0.049;
    //wgt and fat display
  if(_nMeasTypeIdx == 3) {
    short wUn = (short)pApp.m_bodyInfo.nWgtUn;
    if(_maLastData != nil && _maLastData.count > 0)
      wUn = nUnit;
    [_ringMater setMeasVals:fLwgt fat:fLfat un:wUn];
  }
  
  
    //left tips, other data
  float fUnitWgt = fLwgt;
  short nWgtUn = pApp.m_bodyInfo.nWgtUn;
  if(nUnit != nWgtUn) {
    if(nWgtUn == 1)
      fUnitWgt *= _LbtoKg;
    else
      fUnitWgt /= _LbtoKg;
  }
  //fUnitWgt = (short)(fUnitWgt * 100) / 100.0;
  
  //fBmi = (fLwgt / _nHgtMm / _nHgtMm) * 1000000.0;
  
  fLwgt = (short)(fLwgt * 10.0) /10.0;
  float fInitWgt = pApp.m_bodyInfo.fBodyWgt;
  float fGoalWgt = pApp.m_bodyInfo.fGoalWgt;
  float fWgtLoss = (fLwgt>0)? (fInitWgt-fUnitWgt+0.00):0;
  fWgtLoss =  roundf (fWgtLoss * 10) / 10.0;
  float fGoalLen = roundf((fInitWgt - fGoalWgt)* 10) /10.0;
  float fToGoal = fWgtLoss * 100.0 / fGoalLen;
  
  //if(nUnit == 2)
    //fBmi *= _LbtoKg;
  [_ringMater setWgtTips:fGoalWgt wgtLost:fWgtLoss toGoal:fToGoal wgtUn:nWgtUn];
  //[_ivBottom setWgtMeasVal:fLwgt unit:nWgtUn];
  [_ivBottom setWgtMeasVal:pApp.m_bodyInfo.fBodyWgt unit:pApp.m_bodyInfo.nWgtUn];
  [_ivBottom setFatWgtVal:fLfat wgt:fUnitWgt];
}

- (void) updateBodyWgtInfo:(float)fLfat wgt:(float)fWgt
{
  [_ivBottom setFatWgtVal:fLfat wgt:fWgt];
}

- (void) setLastHrtMeasData:(short)nHrate
{
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  //Avg hrate
  double dAvgLstHrt = 0.0;
  short nAvgLstHrt = 0;
  short nMaxLstHrt = 0;
  double dTotalTime = 0;
  NSDate *dtStart = nil, *dtLast = nil;
  NSInteger nLastHrateId = pApp.m_nLastHrtId;
  if(nLastHrateId <= 0)
    nLastHrateId = [pApp loadLastHrateId:_nBodyId sync:NO];
  //short nAvgLstHrt = [pApp loadHrateItemAvg:_nBodyId hRateId:nLastHrateId];
  _maLastData = [NSMutableArray arrayWithArray:[pApp loadHrateItemData:nLastHrateId last:NO]];
  //NSMutableArray* pMaHrate = [NSMutableArray arrayWithArray:[pApp loadHrateData:_nBodyId from:nil to:nil sort:NO last:YES syncDld:NO]];
  NSMutableArray* pMaHrate  = [NSMutableArray arrayWithArray:[pApp loadHrateInfo:nLastHrateId]];
  NSUInteger nCount  = pMaHrate.count;
  if(nCount > 0) {
    H_Rate* pHrate = [pMaHrate objectAtIndex:0];
    if(pHrate != nil)
      dtStart = pHrate.hEnterDate;
  }
  nCount = _maLastData.count;
  if(_maLastData != nil && nCount > 0) {
    for(NSInteger i=0; i<nCount; i++) {
      H_RateItem* pHrtItem = (H_RateItem*)[_maLastData objectAtIndex:i];
      if(pHrtItem == nil)
        continue;
      
      //if(i == 0)
        //dtStart = pHrtItem.hRateTime;
      double dDurSeconds = 0;
      nHrate = pHrtItem.hRateValue.shortValue;
      NSDate* dtMeas = pHrtItem.hRateTime;
      if(dtLast != nil)
        dDurSeconds  = [dtMeas timeIntervalSinceDate:dtLast];
      
      dTotalTime = [dtMeas timeIntervalSinceDate:dtStart];
      dTotalTime -= dDurSeconds;
      if(dTotalTime == 0) {
        dTotalTime = dDurSeconds;
      }
      double dSum = dTotalTime + dDurSeconds;

      if(dAvgLstHrt < 1) {
        dAvgLstHrt = nHrate;
      }
      else if(dSum != 0) {
        dAvgLstHrt = (dAvgLstHrt * dTotalTime + nHrate * dDurSeconds) / dSum;
      }
      
      //max
      if(nMaxLstHrt < nHrate)
        nMaxLstHrt = nHrate;
      
      dTotalTime += dDurSeconds;
      dtLast = dtMeas;
    }
  }
  nAvgLstHrt = (short)(dAvgLstHrt + 0.5);
  
  short nLastHrt = (pApp.m_nLastHrate != 0)?pApp.m_nLastHrate:-1;
  short nCurtAvgHrt = 0;//(pApp.m_nCurtAvgHrt != 0)?pApp.m_nCurtAvgHrt:nAvgLstHrt;
  if(pApp.m_nLastHrtId > 0)
    nCurtAvgHrt = nAvgLstHrt;
  else
   nCurtAvgHrt = (pApp.m_nCurtAvgHrt != 0)?pApp.m_nCurtAvgHrt:nAvgLstHrt;
  
  //
  if(nLastHrt <= 0 && nAvgLstHrt > 0) {
    //_maLastData = [NSMutableArray arrayWithArray:[pApp loadHrateItem:_nBodyId from:nil to:nil sort:NO avg: NO last:YES sync:NO]];
    if(_maLastData != nil && _maLastData.count > 0) {
      H_RateItem* pHrtItem = (H_RateItem*)[_maLastData objectAtIndex:_maLastData.count-1];
      if(pHrtItem != nil && pHrtItem.hRateValue != nil) {
        nLastHrt = pHrtItem.hRateValue.shortValue;
        pApp.m_nLastHrate = nLastHrt;
      }
      
      //debug col
      //nLastHrt = 130;
      int nIdx = [pApp getHrateRngIdx:nLastHrt maxLine:_yMaxLine count:_nDurtBarNumber];
      [_ringMater setHrateVals:nLastHrt colIdx:nIdx];
    }
    else {
      [_ringMater setHrateVals:0 colIdx:0];
    }
    pApp.m_nCurtAvgHrt = nCurtAvgHrt;
  }
  else if(nLastHrt > 0) {
    int nIdx = [pApp getHrateRngIdx:nLastHrt maxLine:_yMaxLine count:_nDurtBarNumber];
    [_ringMater setHrateVals:nLastHrt colIdx:nIdx];
  }
  else {
    [_ringMater setMeasVals:nLastHrt fat:0.0 un:0];
  }
  
  [_ringMater setHrtHrtAvgTips:nCurtAvgHrt];
  
  //[_ivBottom setHrtMeasVal:nAvgLstHrt];
  [_ivBottom setHrtMeasVal:nMaxLstHrt];
  //return nHrtCount;
 
 
    
  /*if(nHrate > 0)
    [_ivBottom setHrtMeasVal:nHrate];
  else if(nAvgLstHrt > 0)
    [_ivBottom setHrtMeasVal:nAvgLstHrt];*/
}

- (void) setLastBdpMeasData:(short)nHpres low:(short)nLpres
{ 
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    //bldp
  short nHbldp = 0, nLbldp = 0;
  double dHbldp = 0.0, dLbldp = 0.0;
  //_maLastData = [pApp loadBdpData:_nBodyId from:nil to:nil sort:NO last:YES];
  //_maLastData = [pApp loadBdpData:_nBodyId from:nil to:nil sort:YES last:YES];
  _maLastData = [NSMutableArray arrayWithArray:[pApp loadBdpAvgData:_nBodyId last:4]];
  
  if(_maLastData != nil && _maLastData.count > 0) {
    N_BdpData* pBldp = (N_BdpData*)[_maLastData objectAtIndex:0];
    if(pBldp != nil && pBldp.bphVal != nil) {
      nHbldp = pBldp.bphVal.shortValue;
      nLbldp = pBldp.bplVal.shortValue;
    }
    NSUInteger nCount = _maLastData.count;
    for(NSUInteger i=0; i<nCount; i++) {
      pBldp = (N_BdpData*)[_maLastData objectAtIndex:i];
      if(pBldp != nil && pBldp.bphVal != nil) {
        dHbldp += pBldp.bphVal.shortValue;
        dLbldp += pBldp.bplVal.shortValue;
      }
    }
    dHbldp /= nCount;
    dLbldp /= nCount;
  }
    //[_ringMater setHrtBldBestTips:nMbldp];
  [_ringMater setHrtBldAvgTips:(short)(dHbldp+0.5) low:(short)(dLbldp+0.5)];
    
    if(nHpres > 0 && nLpres >0) {
        [_ringMater setMeasVals:nHpres fat:nLpres un:0];
        [_ivBottom setBdpMeasVal:nHpres low:nLpres];
    }
    else {
        [_ringMater setMeasVals:nHbldp fat:nLbldp un:0];
        [_ivBottom setBdpMeasVal:nHbldp low:nLbldp];
    }
}

- (void) setLastStepMeasData:(int)nSteps
{
  [_ringMater setMeasVals:nSteps fat:0.0 un:0];
  if(nSteps > 0) {
    [_ivBottom setStepMeasVal:nSteps];
    return;
  }
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    //steps
    int nGsteps = pApp.m_bodyInfo.nGoalStep;
    float fTdists = 0.0; //pApp.m_bodyInfo.fGoalDist;
    float fStepsG = 0;
    int nMsteps = 0;

    _maLastData = [NSMutableArray arrayWithArray:[pApp loadStepsData:_nBodyId from:nil to:nil sort:YES last:YES]];
    if(_maLastData != nil && _maLastData.count > 0) {
        P_Steps* pStep = (P_Steps*)[_maLastData objectAtIndex:0];
        if(pStep != nil) {
            NSDate* dtMeas = pStep.measDate;
            if([pApp dateIsToday: dtMeas]) {
              fTdists = pStep.tDistances.floatValue / 1000.0;
              fTdists *= _KmtoMis;
              nMsteps = pStep.nSteps.intValue;
            }
        }
    }
  
    int nLsteps = 0;
    _maLastData = [NSMutableArray arrayWithArray:[pApp loadStepsData:_nBodyId from:nil to:nil sort:NO last:YES]];
    if(_maLastData != nil && _maLastData.count > 0) {
        P_Steps* pStep = (P_Steps*)[_maLastData objectAtIndex:0];
        if(pStep != nil) {
            nLsteps = pStep.nSteps.intValue;
        }
    }
    if(nMsteps > 0 && nGsteps != 0) {
        fStepsG = nMsteps * 100.0 / nGsteps;
    }
  
  //today's data
  /*NSDate* dtTo = [NSDate date];
  NSDate* dtFr = [dtTo dateByAddingTimeInterval: -86400.0];
  _maLastData = [NSMutableArray arrayWithArray:[pApp loadStepsData:_nBodyId from:dtFr to:dtTo sort:NO last:NO]];
  if(_maLastData != nil && _maLastData.count > 0) {
    P_Steps* pStep = (P_Steps*)[_maLastData objectAtIndex:0];
    //if(pStep != nil) {
      //fTdists = [pStep.;
    //}
  }*/
  
    
    [_ringMater setStepsTips:fTdists gStep:fStepsG mStep:nMsteps lStep:nLsteps];
    
    
    //[_ringMater setMeasVals:nMsteps fat:0.0 un:0];
    //[_ivBottom setStepMeasVal:nMsteps];
    //[_ringMater setOtherValus:fGoalWgt wgtLost:fWgtLoss toGoal:fToGoal avgHrt:nAvgHrt bestBldp:nMbLdp todayDists:fTdists gStep:fStepsG mStep:nMsteps];
}

- (UIImage*) getImageScale:(NSString*) sImgName scale:(float)fRate
{
    UIImage* imgBkgd = [UIImage imageNamed:sImgName];
    UIGraphicsBeginImageContext(CGSizeMake(imgBkgd.size.width * fRate, imgBkgd.size.height * fRate));
    [imgBkgd drawInRect:CGRectMake(0, 0, imgBkgd.size.width * fRate, imgBkgd.size.height * fRate)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    BOOL bIos7 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0;
    if(bIos7) {
        scaledImage = [scaledImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    return scaledImage;
}

- (void) drawMeasRingMeter
{
  //NSString * sImgName = @"";
    [_ringMater setRingImage:_nMeasTypeIdx];
    if(_nMeasTypeIdx == 0) {
      short nLastHrate = 0;
      [_btnAdd setBackgroundImage:[UIImage imageNamed:@"btn-hrate.png"] forState:UIControlStateNormal];
      _lblPlayTips.text = NSLocalizedString(@"Find HRM", nil);
      if(_ncitBleDev.bleDelegate == nil)
        [self setLastHrtMeasData: nLastHrate];
      
      _lblPlusTips.textColor = [UIColor colorWithRed:112.0/255 green:42.0/255 blue:135.0/255 alpha:0.75];
      _lblPlayTips.textColor = [UIColor colorWithRed:112.0/255 green:42.0/255 blue:135.0/255 alpha:0.75];
    }
    else if(_nMeasTypeIdx == 1) {
      short nHpres = 0, nLpres = 0;
      [_btnAdd setBackgroundImage:[UIImage imageNamed:@"btn-bldp.png"] forState:UIControlStateNormal];
      _lblPlayTips.text = @"Find BP";
      [self setLastBdpMeasData:nHpres low:nLpres];
      
      _lblPlusTips.textColor = [UIColor colorWithRed:215.0/255 green:26.0/255 blue:117.0/255 alpha:0.75];
      _lblPlayTips.textColor = [UIColor colorWithRed:215.0/255 green:26.0/255 blue:117.0/255 alpha:0.75];
    }
    else if(_nMeasTypeIdx == 2) {
      int nSteps = 0;
      [_btnAdd setBackgroundImage:[UIImage imageNamed:@"btn-step.png"] forState:UIControlStateNormal];
      _lblPlayTips.text = NSLocalizedString(@"Find Device", nil);
      [self setLastStepMeasData:nSteps];
      
      _lblPlusTips.textColor = [UIColor colorWithRed:0.0/255 green:144.0/255 blue:81.0/255 alpha:0.75];
      _lblPlayTips.textColor = [UIColor colorWithRed:0.0/255 green:144.0/255 blue:81.0/255 alpha:0.75];
    }
    else if(_nMeasTypeIdx == 3) {
      //AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
      //[pApp getUserGoalData:NO];
      float fWgt = 0.0;
      [_btnAdd setBackgroundImage:[UIImage imageNamed:@"btn-weigh.png"] forState:UIControlStateNormal];
      _lblPlayTips.text = NSLocalizedString(@"Find Device", nil);
      [self setLastWgtMeasData:fWgt unit:0 fat:0.0f wat:0.0f];
        _ncitBleDev.delegate = self;
      _lblPlusTips.textColor = [UIColor colorWithRed:0.0/255 green:140.0/255 blue:189.0/255 alpha:0.75];
      _lblPlayTips.textColor = [UIColor colorWithRed:0.0/255 green:140.0/255 blue:189.0/255 alpha:0.75];
    }
}

//test insert pedo stes
-(void) insertTestStepData
{
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSString* sInitDtFmt = pApp.dtFmt.dateFormat;
    NSDateFormatter* dtFmt = pApp.dtFmt;
    [dtFmt setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
    
    NSInteger nBodyId = pApp.m_bodyInfo.m_nBodyId;
    NSDate* dtMeas = [pApp.dtFmt dateFromString:@"09/01/2015 10:23:45"];
    [pApp insertStepsData:nBodyId step:30 dist:0.1 calory:0.2 date:dtMeas add:NO toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/02/2015 11:23:45"];
    [pApp insertStepsData:nBodyId step:50 dist:0.2 calory:0.3 date:dtMeas add:NO toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/03/2015 12:23:45"];
    [pApp insertStepsData:nBodyId step:80 dist:0.3 calory:0.4 date:dtMeas add:NO toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/04/2015 13:23:45"];
    [pApp insertStepsData:nBodyId step:110 dist:0.4 calory:0.5 date:dtMeas add:NO toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/05/2015 14:23:45"];
    [pApp insertStepsData:nBodyId step:140 dist:0.5 calory:0.6 date:dtMeas add:NO toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/15/2015 15:23:45"];
    [pApp insertStepsData:nBodyId step:100 dist:1.1 calory:0.7 date:dtMeas add:NO toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/16/2015 16:23:45"];
    [pApp insertStepsData:nBodyId step:450 dist:2.2 calory:0.8 date:dtMeas add:NO toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/17/2015 8:23:45"];
    [pApp insertStepsData:nBodyId step:120 dist:1.3 calory:0.9 date:dtMeas add:NO toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/18/2015 9:23:45"];
    [pApp insertStepsData:nBodyId step:250 dist:1.4 calory:1.0 date:dtMeas add:NO toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/19/2015 10:23:45"];
    [pApp insertStepsData:nBodyId step:300 dist:1.5 calory:1.1 date:dtMeas add:NO toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/20/2015 11:23:45"];
    [pApp insertStepsData:nBodyId step:250 dist:1.6 calory:1.2 date:dtMeas add:NO toSvr:YES];
    
    dtMeas = [pApp.dtFmt dateFromString:@"09/21/2015 12:23:45"];
    [pApp insertStepsData:nBodyId step:390 dist:1.7 calory:1.3 date:dtMeas add:NO toSvr:YES];
  
    dtMeas = [pApp.dtFmt dateFromString:@"09/23/2015 10:23:45"];
    [pApp insertStepsData:nBodyId step:125 dist:0.6 calory:0.45 date:dtMeas add:NO toSvr:YES];
    
    [pApp.dtFmt setDateFormat:sInitDtFmt];
}


//action
//-(void)selectLeftAction:(id)sender  
//{
//  [self showMenuFromNavigationBarItem:sender];
//  //AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//  //test
//  /*NSString* sUrl = [NSString stringWithFormat:@"Mfw"];
//  NSDictionary* measInfo = @{
//                             @"_sDevId": @"BFS221-5E40353",
//                             @"_sCurtDateTime": @"2016-02-29 12:34:56",
//                             @"_nType" : @"2"
//                             };
//  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"POST" url:sUrl data:measInfo];
//  request.timeoutInterval = 10.0;
//  [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//    if(data == nil)
//      return;
//    
//    NSError *e = nil;
//    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];;
//    for(NSDictionary *item in jsonArray) {
//      //NSLog(@"Item: %@", item);
//      NSNumber* nBodyId = [item objectForKey: @"_nBodyId"];
//      NSNumber* nSex = [item objectForKey:@"_nGender"];
//      NSNumber* nYears = [item objectForKey:@"_nOldYear"];
//      NSNumber* nHgtCm = [item objectForKey:@"_nHgtCm"];
//      
//      NSNumber* nAthLvl = [item objectForKey:@"_nAthLvl"];
//      NSString* sCurtDt = [item objectForKey:@"_sCurtDateTime"];
//      int m = 0;
//    }
//  }];*/
//  //test end
//  
//  /*if([pApp isUserMgr]) {
//    [self showMenuFromNavigationBarItem:sender];
//  }
//  else {
//    UIStoryboard* mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//    UIBodyProfileViewCtrl* vcBodyProf = [mainStory instantiateViewControllerWithIdentifier:@"bodyProfViewCtrl"];
//    [pApp.m_pNavController pushViewController:vcBodyProf animated:YES];
//  }*/
//}

- (void) onLoadHrdDataRcd
{
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp enterPageWithRes:@"hrdRcdViewCtrl"];
}

- (void) onLoadBdpDataRcd
{
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp enterPageWithRes:@"bdpRcdViewCtrl"];
}

- (void) onLoadStepDataRcd
{
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp enterPageWithRes:@"stepRcdViewCtrl"];
}

- (void) onLoadWgtDataRcd
{
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp enterPageWithRes:@"wgtRcdViewCtrl"];
}

- (void) onWiFiScanCard:(id)sender
{
  BOOL bScan = _swFiFiScanCard.on;
  //_lblMsg.text = bScan?@"Card scan": NSLocalizedString(@"Cancel", nil);
  if(bScan) {
    if(_wifiScaleTimer == nil) {
      AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
      
      [_ringMater setMeasVals:0.0 fat:0.0 un:0];
      //test get
      //NSString* sUrl = [NSString stringWithFormat:@"Mfw/%@", sCode];
      //NSMutableURLRequest *request = [pApp requestWebApiRouter:@"GET" url:sUrl data:nil];
      //test get
      NSString* sUrl = [NSString stringWithFormat:@"Mfw/%ld", (long)_nBodyId];
      NSDictionary* measInfo = @{
                                 @"_sDevId": @"00000000",
                                 @"_sTagId": @"00000000",
                                 @"_nType" : @"1"
                                 };
      NSMutableURLRequest *request = [pApp requestWebApiRouter:@"PUT" url:sUrl data:measInfo];
      //request.timeoutInterval = 10.0;
      
      NSURLSessionDataTask *task = [_netSession dataTaskWithRequest:request];
      [task resume];
      
      _wifiScaleTimer = [NSTimer scheduledTimerWithTimeInterval:2.00 target:self selector:@selector(onWiFiMeasTimer:) userInfo:@"00000000" repeats:YES];
      _lblMsg.text = @"Scan your TagID then step on WiFi scale";
    }
    
  }
  else {
    if(_wifiScaleTimer != nil) {
      [_wifiScaleTimer invalidate];
      _wifiScaleTimer = nil;
    }
    _lblMsg.text = @"Cancel Scan TagID";
  }
}

- (void) tapImgBtnView:(id)sender
{
  //debug
  //AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  //NSString* sName = pApp.m_bodyInfo.sFirst;
    
  if(_nMeasTypeIdx == 3)
    _swFiFiScanCard.on = NO;
  
  /*if(sender == _btnStopMeas) {
    //_ncitBleDev.bleDelegate = nil;
    [self ProcrHrmStopMeas];
    return;
  }*/
  if(_nMeasTypeIdx != 0) {
    [self ProcrHrmStopMeas];
  }
  else if(sender != nil && _ncitBleDev.bConnBleDev) {
    [self ProcrHrmStopMeas];
    return;
  }
  
  if(_bConnBleDev) {
    _bSyncStepDataEnd = NO;
    [_ncitBleDev stopMeas];
    _bConnBleDev = NO;
    if(_nMeasTypeIdx == 2 && _nSteps > 0) {
      AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
      NSDate* dtNow = [NSDate date];
      [pApp insertStepsData:pApp.m_bodyInfo.m_nBodyId step:_nSteps dist:_fDists calory:_fCalors date:dtNow add:NO toSvr:YES];
      _nSteps = 0;
    }
        
    [self setLastStepMeasData:0];
        
    UIImage* iBtn = [UIImage imageNamed:@"ic-play.png"];
    [_btnPlay setBackgroundImage:iBtn forState:UIControlStateNormal];
    
    _ivBottom.hidden = NO;
    _btnDownShow.hidden = YES;
    
    return;
  }
  //_lblMsg.text = (sender == _btnAdd)? @"add": @"play";
  if(sender == _btnPlay || sender == nil) {
    //[_ncitBleDev stopMeas];
    [NSThread sleepForTimeInterval:0.05];
      
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if(_nMeasTypeIdx != 3) {
      if(!pApp.m_bSupportBle) {
        _lblMsg.text = NSLocalizedString(@"TurnOnBleTip", nil);//@"Please turn your BLE on with setting";
        AudioServicesPlaySystemSound(1112);
        return;
      }
    }
    if(_nMeasTypeIdx == 0 ) {
      [self onlineHrateMeas];
    }
    else if(_nMeasTypeIdx == 1) {
      [self onlineBldPresMeas];
    }
    else if(_nMeasTypeIdx == 2) {
      [self onlineStepMease];
    }
    else if(_nMeasTypeIdx == 3) {
      [self onlineWgtMeas];
    }
    [pApp CloseScaleHost];
    
    _lblMsg.text = NSLocalizedString(@"Begin...", nil);
    _lblMsg.textColor = [UIColor colorWithRed:112.0/255 green:42.0/255 blue:135.0/255 alpha:0.75];
  }
  else {
    /*AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if(pApp.m_bSupportBle && _ncitBleDev.bConnBleDev)
      [_ncitBleDev stopMeas];*/
    
    //_lblMsg.text = @"Still in developing...";
    if(_nMeasTypeIdx == 0 ) {
      [self onLoadHrdDataRcd];
    }
    else if(_nMeasTypeIdx == 1) {
      [self onLoadBdpDataRcd];
    }
    else if(_nMeasTypeIdx == 2) {
      [self onLoadStepDataRcd];
    }
    else if(_nMeasTypeIdx == 3) {
      [self onLoadWgtDataRcd];
      if(_wifiScaleTimer != nil) {
        [_wifiScaleTimer invalidate];
        _wifiScaleTimer = nil;
      }
    }
    
    //debug
    /*sName = pApp.m_bodyInfo.sFirst;
    sName = pApp.m_bodyInfo.sLast;
    sName = @"";*/
  }
  _lblMsg.textColor =  _lblPlusTips.textColor;
  if(_nMeasTypeIdx == 0) {
    AudioServicesPlaySystemSound(1109);
  }
}

- (CGFloat*) getStoreRngDurTime
{
  return _pfDurHrate;
}

- (void) onlineHrateMeas
{
  _bFirstShow = NO;
  _lblMsg.text = NSLocalizedString(@"Hrate Meas", nil);
  _ncitBleDev.bleDelegate = nil;
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  HeaRateViewCtrl* pHrmViewCtrl = (HeaRateViewCtrl*)[pApp enterPageWithRes:@"heaRateViewCtrl"];
    pHrmViewCtrl.delegate = self;
  [pHrmViewCtrl setHrmMeasPoint:_nHrateId hrate:_pHrate dtStart:_dtHrmPoint calry:_fCalry dur:_pfDurHrate size:nDurCount];
}

- (void) onlineBldPresMeas
{
    _lblMsg.text = NSLocalizedString(@"Bld pres Meas", nil);
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp enterPageWithRes:@"bldPresViewCtrl"];
}

- (void) onlineStepMease
{
    //test insert data
    //[self insertTestStepData];
    //test ins data end
    _bSyncStepDataEnd = NO;
    _pBlePedoChar = nil;
    
    _ncitBleDev.bAutoConnect = YES;
    _ncitBleDev.bleDelegate = self;
    //if([_ncitBleDev loadSavedDevice:_nMeasTypeIdx])
        //return;
    
    if(_cbdPedoDev == nil) {
      CGRect frame = [[UIScreen mainScreen] bounds];
      CGFloat W = frame.size.width;
      CGFloat H = frame.size.height;
      BOOL bIpad = W > 500;
      BOOL bIp4s = H <= 480;
        
      CGFloat fSize = bIpad? 420: 280;
      CGFloat xPos = (W - fSize) / 2.0;
      CGFloat yPos = (H - fSize) /  2.8;
      if(bIp4s)
        yPos += 30;
        
      _cbdPedoDev = [[UIChooseBleDev alloc] initWithFrame:CGRectMake(xPos, yPos, fSize, fSize * (bIp4s?1.15:1.25))];
      [self.view addSubview:_cbdPedoDev];
    }
    _cbdPedoDev.hidden = NO;
    [_cbdPedoDev resetCtrls];
  [_ringMater updPedoBattery:0];
}

- (void) onlineWgtMeas
{
  if(_wmtWgtType == nil) {
    CGRect frame = [[UIScreen mainScreen] bounds];
    CGFloat W = frame.size.width;
    CGFloat H = frame.size.height;
      
    CGFloat xPos = W / 5.0;
    CGFloat fWidHgt = W - xPos * 2.0;
    CGFloat yPos = (H - fWidHgt) / 2.0 - 25;
    _wmtWgtType = [[UIWgtMeasType alloc] initWithFrame:CGRectMake(xPos, yPos, fWidHgt, fWidHgt)];
    
    _wmtWgtType.layer.masksToBounds = YES;
    _wmtWgtType.layer.cornerRadius = 12;
  }
  [_wmtWgtType addWgtTypeButs];
  _wmtWgtType.wtDelegate = self;
  [self.view addSubview:_wmtWgtType];
}

//meas button action
- (void) onWaitTest
{
  _lblMsg.text = NSLocalizedString(@"Waiting test...", nil);
  AudioServicesPlaySystemSound(1112);
  
  /*AVAudioSession *audioSession = [AVAudioSession sharedInstance];
  NSError *err = nil;
  [audioSession setCategory: AVAudioSessionCategoryPlayback  error:&err];
  AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
  NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"sample" withExtension:@"caf"];
  AVAudioPlayer* avSound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
  [avSound play];*/
}

//- (void) onMeasButtonsAct:(id)sender
 - (void) onButtonTaps:(int)nTapIdx;
{
    _deviceName.text = @"";
  [self stopWgtTypeCtrl];
  if(!_cbdPedoDev.hidden)
    _cbdPedoDev.hidden = YES;
    
  _nMeasTypeIdx = nTapIdx;
  NSString* sSelMeas = @"";
//  BOOL bConnBleHrm = _ncitBleDev.bConnBleDev;
    BOOL bConnBleHrm = NO;
  if(nTapIdx == 0) {
    sSelMeas = NSLocalizedString(@"Heart Rate", nil);
    UIImage* iBtn = [UIImage imageNamed:(bConnBleHrm?@"btn-stop.png": @"btn-search.png")];
    [_btnPlay setBackgroundImage:iBtn forState:UIControlStateNormal];
    _lblMsg.textColor = [UIColor colorWithRed:112.0/255 green:42.0/255 blue:135.0/255 alpha:0.75];
       _deviceName.hidden = NO;
      _deviceName.textColor = [UIColor colorWithRed:112.0/255 green:42.0/255 blue:135.0/255 alpha:0.75];
  }
  else if(nTapIdx == 1) {
    sSelMeas = NSLocalizedString(@"Blood Pressure", nil);
    UIImage* iBtn = [UIImage imageNamed:(bConnBleHrm?@"btn-stop.png": @"btn-search-red.png")];
    [_btnPlay setBackgroundImage:iBtn forState:UIControlStateNormal];
     _lblMsg.textColor = [UIColor colorWithRed:215.0/255 green:26.0/255 blue:117.0/255 alpha:0.75];
      _deviceName.hidden = YES;
  }
  else if(nTapIdx == 2) {
    sSelMeas = NSLocalizedString(@"Pedometer", nil);
    UIImage* iBtn = [UIImage imageNamed:(bConnBleHrm?@"btn-stop.png": @"btn-search-green.png")];
    [_btnPlay setBackgroundImage:iBtn forState:UIControlStateNormal];
    _lblMsg.textColor = [UIColor colorWithRed:0.0/255 green:144.0/255 blue:81.0/255 alpha:0.75];
     _deviceName.hidden = YES;
      
  }
  else if(nTapIdx == 3) {
    sSelMeas = NSLocalizedString(@"Weight", nil);
    UIImage* iBtn = [UIImage imageNamed:(bConnBleHrm?@"btn-stop.png": @"btn-search-blue.png")];
    [_btnPlay setBackgroundImage:iBtn forState:UIControlStateNormal];
    _lblMsg.textColor = [UIColor colorWithRed:0.0/255 green:140.0/255 blue:189.0/255 alpha:0.75];
    _deviceName.hidden = NO;
      
      _deviceName.textColor = [UIColor colorWithRed:0.0/255 green:140.0/255 blue:189.0/255 alpha:0.75];
  }
  _lblMsg.text = sSelMeas;
  _lblHrateElaped.text = @"";
  _ncitBleDev.nDevTypeIdx = _nMeasTypeIdx;
    
  
  if(!_bFirstShow) {
    [self drawMeasRingMeter];
    if(_nMeasTypeIdx == 0) {
      BOOL bConnBleHrm = _ncitBleDev.bConnBleDev;
      _lblPlayTips.text = bConnBleHrm? @"STOP": NSLocalizedString(@"Find HRM", nil);
      UIImage* iBtn = [UIImage imageNamed:(bConnBleHrm?@"btn-stop.png": @"btn-search.png")];
      [_btnPlay setBackgroundImage:iBtn forState:UIControlStateNormal];
    }
    
    if(_wifiScaleTimer != nil) {
      [_wifiScaleTimer invalidate];
      _wifiScaleTimer = nil;
    }
    
    [_ringMater setCtrlFontColor:_nMeasTypeIdx];
    AudioServicesPlaySystemSound(1109);
  }
  
  //if(nTapIdx != 0)
     //[self ProcrHrmStopMeas];
  
  _swFiFiScanCard.hidden = YES;//nTapIdx != 3;
  _lblScanTips.hidden = YES; //_swFiFiScanCard.hidden;
  
  //debug
  /*AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSString* sName = pApp.m_bodyInfo.sFirst;//[pApp isNetWorkConnAvailable];
  sName = pApp.m_bodyInfo.sLast;
  sName = @"";*/
}

- (void) ScanedQRcode:(NSString*)sCode
{
  if(_wifiScaleTimer != nil) {
    [_wifiScaleTimer invalidate];
    _wifiScaleTimer = nil;
  }
  
  [_wmtWgtType rmvWgtTypeButs];
  _wmtWgtType.wtDelegate = nil;
  [_wmtWgtType removeFromSuperview];
  
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSString* sInfo = [NSString stringWithFormat:@"%@ : %@", [pApp connedWifiSSID], sCode];
  _lblMsg.text = sInfo;
  _lblMsg.textColor = [UIColor colorWithRed:112.0/255 green:42.0/255 blue:135.0/255 alpha:0.75];
  [self sendCardNotoHttpSvr:sCode];
  
  /*NSString* sInfo = [self turnOnWiFiConn];
  if(sInfo != nil) {
    sInfo = [sInfo stringByAppendingFormat:@" : %@", sCode];
    _lblMsg.text = sInfo;
    _lblMsg.textColor = [UIColor whiteColor];
        
    [self sendCardNoToScale: NO code:sCode];
  }*/
}

- (void) onWiFiMeasTimer:(NSString*)sCode
{
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  //test get
  //NSString* sUrl = [NSString stringWithFormat:@"Mfw/%@", sCode];
  //NSMutableURLRequest *request = [pApp requestWebApiRouter:@"GET" url:sUrl data:nil];
  //test get
  NSString* sUrl = [NSString stringWithFormat:@"Mfw/%ld", (long)_nBodyId];
  /*NSDictionary* measInfo = @{
                             @"_sDevId": sCode,
                             @"_sTagId": _sTagId,
                             @"_nType" : @"1"
                             };*/
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"DELETE" url:sUrl data:nil];
  //request.timeoutInterval = 10.0;
  
  NSURLSessionDataTask *task = [_netSession dataTaskWithRequest:request];
  [task resume];
}

- (void) sendCardNotoHttpSvr:(NSString*)sCode
{
  if(_wifiScaleTimer == nil) {
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    [_ringMater setMeasVals:0.0 fat:0.0 un:pApp.m_bodyInfo.nWgtUn];
    //test get
    //NSString* sUrl = [NSString stringWithFormat:@"Mfw/%@", sCode];
    //NSMutableURLRequest *request = [pApp requestWebApiRouter:@"GET" url:sUrl data:nil];
    //test get
    NSString* sUrl = [NSString stringWithFormat:@"Mfw/%ld", (long)_nBodyId];
    NSDictionary* measInfo = @{
                               @"_sDevId": sCode,
                               @"_sTagId": _sTagId,
                               @"_nType" : @"1"
                               };
    NSMutableURLRequest *request = [pApp requestWebApiRouter:@"PUT" url:sUrl data:measInfo];
    //request.timeoutInterval = 10.0;
    
    NSURLSessionDataTask *task = [_netSession dataTaskWithRequest:request];
    [task resume];
    
    _wifiScaleTimer = [NSTimer scheduledTimerWithTimeInterval:2.00 target:self selector:@selector(onWiFiMeasTimer:) userInfo:sCode repeats:YES];
  }
  
  
  /*NSData *data= [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
  if (data != nil) {
  //[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
    
    // handle response
    NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    NSError *e = nil;
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
    for(NSDictionary *item in jsonArray) {
      //NSLog(@"Item: %@", item);
      NSString* sWgtVal = [item objectForKey:@"_fWgtVal"];
      NSString* sWgtUn = [item objectForKey:@"_nWgtUnit"];
      NSString* sFatVal = [item objectForKey: @"_fFatVal"];
      NSString* sWatVal = [item objectForKey:@"_fWatVal"];
      [_ringMater setMeasVals:sWgtVal.floatValue fat:sFatVal.floatValue un:(short)sWgtUn.intValue];
    }
  
  };*/
  
}

- (void) sendCardNoToScale:(BOOL)bCancel code:(NSString*) sDevCode
{
    char szTagIdNo[64];
    BOOL bToSvr = !bCancel;//[self.svrType selectedSegmentIndex] == 1;
    
    if(bCancel)
        strcpy(szTagIdNo, bToSvr? "1234 TagIdClr=": "TagIdClr=");
    else
        strcpy(szTagIdNo, bToSvr? "1234 TagId=": "TagId=");
    strcat(szTagIdNo, [_sTagId UTF8String]);
    
    if(bToSvr) {
        NSString* sDevId = sDevCode;
        //if([sDevId isEqual:@"********"])
            //sDevId = _sDevId;
        strcat(szTagIdNo, "DevId=");
        strcat(szTagIdNo, [sDevId UTF8String]);
    }
    strcat(szTagIdNo, "\r\n");
    
    //if(!bToSvr && ![_socketSvr isConnNetwork])
        //[self turnOnScaleSocket:YES];
    [_NcitWiFiDev sendData:szTagIdNo Alert:NO];
    //_bSendTagDevInfo = YES;
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
  if (data == nil)
    return;
  
  //[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
    
  // handle response
  NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
  if(sRecv == nil || sRecv.length < 9)
    return;
  if([sRecv rangeOfString:@"error"].location != NSNotFound)
    return;
  
  NSError *e = nil;
  NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
  if(jsonArray == nil)
    return;
  
  for(NSDictionary *item in jsonArray) {
    dispatch_sync(dispatch_get_main_queue(), ^{
    //NSLog(@"Item: %@", item);
      NSString* sMeasId = [item objectForKey:@"_nMeasWgtId"];
      NSString* sDevId = [item objectForKey:@"_sDevId"];
      NSString* sTagId = [item objectForKey:@"_sTagId"];
      NSString* sWgtVal = [item objectForKey:@"_fWgtVal"];
      NSString* sWgtUn = [item objectForKey:@"_nWgtUnit"];
      NSString* sFatVal = [item objectForKey: @"_fFatVal"];
      NSString* sWatVal = [item objectForKey: @"_fWatVal"];
      NSString* sOth1 = [item objectForKey: @"_nOthVal1"];
      NSString* sOth2 = [item objectForKey: @"_nOthVal2"];
      long long nOth = ((long long)(sOth1.integerValue)) << 32;
      nOth += sOth2.intValue;
      NSString* sDtMeas = [item objectForKey: @"_sCurtDateTime"];
      //NSString* sWatVal = [item objectForKey:@"_fWatVal"];
      if(sWgtVal.floatValue > 0 || sFatVal.floatValue > 0) {
        AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        NSString* sFmt = pApp.dtFmt.dateFormat;
        [pApp.dtFmt setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate* dtMeas = [pApp.dtFmt dateFromString:sDtMeas];
        
        //[self insWgtData:sDevId card:sTagId data:sWgtVal.floatValue unit:sWgtUn.intValue dtScale:sDtMeas  toSvr:NO];
        [pApp insertWiFiWgtData:sMeasId.integerValue DevId:sDevId card:sTagId data:sWgtVal.floatValue unit:sWgtUn.intValue
                         bodyId:pApp.m_bodyInfo.m_nBodyId dtScale:sDtMeas];
        [pApp insertFatData:pApp.m_bodyInfo.m_nBodyId fat:sFatVal.floatValue/10 wat:sWatVal.floatValue/10 hgt:0.0 unit:10 oth:nOth date:dtMeas toSvr:NO];
        
        //[pApp CloseScaleHost];
        [self setLastWgtMeasData:sWgtVal.floatValue unit:sWgtUn.intValue fat:sFatVal.floatValue/10  wat:sWatVal.floatValue/10];
        
        [pApp.dtFmt setDateFormat:sFmt];
        [_wifiScaleTimer invalidate];
        _wifiScaleTimer = nil;
        _swFiFiScanCard.on = NO;
        AudioServicesPlaySystemSound(1115);
      }
    });
  }
}

//wgt dev type delegate
- (void) onWgtTypeChged:(short)nWgtIdx
{
  _nWgtTypeIdx = nWgtIdx;
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  [pApp CloseScaleHost];
    
  if(nWgtIdx == 1) {
    [self stopWgtTypeCtrl];
        
    if(_ncitBleDev != nil) {
      [_ringMater resetMeasVals];
      _ncitBleDev.bleDelegate = self;
      [_ncitBleDev startMeas:nil];
      //[_ncitBleDev startMeas:@"FFE0"];
        _lblMsg.textColor = [UIColor colorWithRed:0.0/255 green:140.0/255 blue:189.0/255 alpha:0.75];
      _lblMsg.text = @"Waiting...";
    }
  }
  else if(nWgtIdx == 2) {
    //[self hideMemberUserCtrls: NO];
    
    [self stopWgtTypeCtrl];
    _lblMsg.text = NSLocalizedString(@"BFS200 WiFi Scale, Step On Scale", nil);
    
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NcitWiFiDev* ncitWiFiDev = pApp.m_ncitWiFiDev;
    [pApp ConnWiFiScaleHost:YES IpAddr:NULL Port:0];
    ncitWiFiDev.svrDelegate = self;
  }
  else if(nWgtIdx == 3) {
    [self stopWgtTypeCtrl];
    [_ringMater setMaualLabel];
    _lblMsg.text = NSLocalizedString(@"Menual Wgt Enter.", nil);//[NSString stringWithFormat:@"menual Wgt enter."];
  }
  else {
    _lblMsg.text = NSLocalizedString(@"Scan QR code on DEV.", nil);
  }
  
  [_ringMater setManualMode:nWgtIdx == 3];
  
  if(nWgtIdx == 1) {
    if (!pApp.m_bSupportBle) {
      _lblMsg.text = NSLocalizedString(@"TurnOnBleTip", nil);//@"Please turn your BLE on with setting";
      AudioServicesPlaySystemSound(1112);
    }
    [_ncitBleDev setConnBleName:@"ACCURO-YUNMAI"];
  }
}

//wifi function
- (NSString*) turnOnWiFiConn
{
     AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    /*_dLastWgtVal = 0.0;
    _nLastWgtVal = 0;
    _bFixBleUser = NO;
    _bConnBleScale = NO;*/
    
    //BOOL bCellConn = NO;
    BOOL bConnHost = pApp.m_bHostConn;
    if(!bConnHost) {
        //eWgtAppDelegate *appDelegate = (eWgtAppDelegate *)[[UIApplication sharedApplication] delegate];
        //bCellConn = YES;//appDelegate.bCellConn;
        bConnHost = [pApp ConnScaleHost:YES IpAddr:NULL];
    }
    NSString* sConnSsid = [pApp connedWifiSSID];

    if(!bConnHost) {
        _lblMsg.text = NSLocalizedString(@"No App Server Connection!", nil);//@"Not connected with Accuro Device ";
        _lblMsg.textColor = [UIColor redColor];
        AudioServicesPlaySystemSound(1112);
        return nil;
    }
    
    //bConnWiFi = [self wifiConnChged: _wifiScaleHost];
    //_lblMsg.text = sConnSsid;
    _NcitWiFiDev.svrDelegate = self;
     [_ringMater resetMeasVals];
    return sConnSsid;
}

-(float) drawWgtChart:(NSString*)sLine {
    float dWgtVal = 0;
    NSArray *listItems = [sLine componentsSeparatedByString:@" "];
    NSUInteger nCount = [listItems count];
    if(nCount == 5 && [[listItems objectAtIndex:0] hasPrefix:@"&"]) { //error from scale
        return 0.0;
    }
    
    BOOL bNewVer = TRUE;
    //check IS200
    Boolean bIS200 = NO;
    Boolean bRis200 = NO;
    Boolean bDbs200 = NO;
    BOOL bDbs210 = NO;
    //BOOL dBfs210 = NO;
    if(nCount > 1) {
        NSString* sMsg = [listItems objectAtIndex:1];
        NSRange rng = [sMsg rangeOfString:@"IS200"];
        bIS200 = rng.location != NSNotFound;
        if(!bIS200) {
            bRis200 = [sMsg hasPrefix:@"RIS2"];
        }
        bDbs200 = [sMsg hasPrefix:@"DBS200"] || [sMsg hasPrefix:@"DB200"];
        bDbs210 = [sMsg hasPrefix:@"DBS2"] || [sMsg hasPrefix:@"BFS2"];
        //dBfs210 = [sMsg hasPrefix:@"BFS2"];
    }
    //_bBabyScaleData = bRis200;
    if(nCount < 5 && bDbs210)
        return 0.0;
    
    if(nCount == 5) {
        if([sLine hasPrefix:@"Weight:   "]) {
            bNewVer = FALSE;
            NSString* sWgt = [sLine substringFromIndex:10];
            if([sWgt hasSuffix:@"\r\n"])
                sWgt = [sWgt stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
            NSDate* date = [[NSDate date] dateByAddingTimeInterval:-6*60*60];
            sLine = [NSString stringWithFormat:@"0000000000 %@ %@", sWgt, [date descriptionWithLocale:nil]];
            listItems = [sLine componentsSeparatedByString:@" "];
        }
        else {
            bNewVer = TRUE;
        }
    }
    else if(!bIS200 && nCount < 7) {
        //_lblState.text = @"......";
        char* szLine = (char*)[sLine UTF8String];
        szLine[0] = 'd';
        szLine[1] = ':';
        szLine[2] = 'n';
        szLine[3] = ' ';
        sLine = [NSString stringWithUTF8String: szLine];
        listItems = [sLine componentsSeparatedByString:@" "];
        if([listItems count] < 7)
            return 0;
    }
    
    int nIdx = bNewVer? 1: 0;
    NSString *sCNo = @"00000000";
    NSString *sSNo = [listItems objectAtIndex:nIdx++];
    
    if(bNewVer)
        sCNo = [listItems objectAtIndex:nIdx++];
    NSString *sWgt = [listItems objectAtIndex:nIdx++];
    NSString *sUn = [listItems objectAtIndex:nIdx++];
    short nUn = [sUn hasPrefix:@"kg"]? 1: 2;
    NSString *sDtOz = @"";
    if(nCount >= 7)
        sDtOz = [NSString stringWithFormat:@"%@ %@", [listItems objectAtIndex:nIdx+0], [listItems objectAtIndex:nIdx+1]];

    
    /*BOOL bBioScan = [sCNo isEqualToString:@"already"] || [sCNo isEqualToString:@"register"];
    //if(swCheck.on && !bIS200) {
    if(!bIS200 && !bDbs200 && !bBioScan) {
        if(![_UserCardNo hasPrefix: sCNo]) {
            _lblState.text = @"ID Not Matched!";
            return 0.0;
        }
    }
    else if(bBioScan) {
        if([sCNo isEqualToString:@"register"])
            sCNo = [listItems objectAtIndex:7];
        else
            sCNo = [listItems objectAtIndex:4];
        if([_UserCardNo isEqualToString:sCNo]) {
            _bWiFiBioScan = YES;
            if(!_actIndicator.isHidden)
                [_actIndicator stopAnimating];
            _lblInfo.text = NSLocalizedString(@"BioScan", nil);// @"BIO Scan";
            _lblState.text = NSLocalizedString(@"WiFiStepon", nil);
            _btnRfid.selected = YES;
            AudioServicesPlaySystemSound(1115);
            return 0.0;
        }
    }*/
    
    
    dWgtVal = [sWgt floatValue];
    
    //bottom text and stored
    /*if(bIS200) {
        if (nUn == 2) {
            listItems = [sDtOz componentsSeparatedByString:@" "];
            if([listItems count] > 1) {
                NSString *sTxt = [listItems objectAtIndex:0];
                dWgtVal += [sTxt floatValue] / 16;
            }
        }
        //sDtOz = [[NSDate date] descriptionWithLocale:[NSLocale currentLocale]];
        sDtOz = [_dtFormat stringFromDate:[NSDate date]];
    }
    else if(bRis200) {
        //sDtOz = [[NSDate date] description];
        sDtOz = [_dtFormat stringFromDate:[NSDate date]];
    }*/
    _lblMsg.text = [NSString stringWithFormat:@"(%@) %@", sCNo, sDtOz];
    //NSString* sMeasId = @"0";
    //if(nCount > 7)
        //sMeasId = [listItems objectAtIndex:7];
  [self insWgtData:sSNo card:sCNo data:dWgtVal unit:nUn dtScale:sDtOz toSvr:NO];
    
    _nWgtUnit = nUn;
    return dWgtVal;
}

- (float)showData:(NSString *)sRecv {
    if([sRecv rangeOfString:@"\n"].location != NSNotFound)
        sRecv = [sRecv stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    if([sRecv rangeOfString:@"\r"].location != NSNotFound)
        sRecv = [sRecv stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    
    float dWgtVal = 0;
    if ([sRecv isKindOfClass:[NSString class]]) {
        dWgtVal = [self drawWgtChart:sRecv];
    }
    //NSString *sCount = [NSString stringWithFormat: @"%i", ++_RecvCount];
    //lblMsg.text = sCount;
    
    return dWgtVal;
}

- (void) recvedWiFiScaleData: (NSMutableString *) sLine {
    /*if(_sBodyId == nil || _sBodyId.integerValue < 0) {
        _lblMsg.text = NSLocalizedString(@"NoLoginTip", nil);
        _lblMsg.textColor = [UIColor whiteColor];
        AudioServicesPlaySystemSound(1112);
        return;
    }*/
    if(sLine == nil)
        return;
    if ([sLine hasPrefix:@"bye!"]) {
        [_NcitWiFiDev turnConnOff];
        AudioServicesPlaySystemSound(1112);
        return;
    }
    
    NSArray *listItems = [sLine componentsSeparatedByString:@" "];
    NSUInteger nCount = [listItems count];
    if(nCount == 3 || nCount == 5 || nCount == 7) {
        NSString* sProdSn = [listItems objectAtIndex:1];
        NSString* sCardNo = [listItems objectAtIndex:2];
        
        _lblMsg.text = [NSString stringWithFormat:@"%@ : %@", sProdSn, sCardNo];
        if(nCount == 3) {
            //[self switchUserByCard:sProdSn card:sCardNo count:nCount];
            //_sDevId = sProdSn;
            return;
        }
    }
    
    float dWgtVal = [self showData:sLine];
    _bFixBleUser = NO;
    
    [_ringMater setMeasVals: dWgtVal fat:0.0 un:0];
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp CloseScaleHost];
    
    [self setLastWgtMeasData:dWgtVal unit:_nWgtUnit fat:0.0f wat:0.0f];
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
        AudioServicesPlaySystemSound(1115);
    else
        AudioServicesPlaySystemSound(1315);
}

- (void) recvedHrateData:(short)nHrate
{
 
  if(_nMeasTypeIdx != 0) {
    if(_nMeasTypeIdx == 1) {
      _lblPlayTips.text = NSLocalizedString(@"Find Device", nil);
    }
    else if(_nMeasTypeIdx == 2) {
      _lblPlayTips.text = NSLocalizedString(@"Find Device", nil);
    }
    else if(_nMeasTypeIdx == 3) {
      _lblPlayTips.text = NSLocalizedString(@"Find Device", nil);
    }
    UIImage* iBtn = [UIImage imageNamed:@"btn-search.png"];
    [_btnPlay setBackgroundImage:iBtn forState:UIControlStateNormal];
  }
  
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  int nIdx = [pApp getHrateRngIdx:nHrate maxLine:_yMaxLine count:_nDurtBarNumber];
  
  BOOL bNotHrmUi = _nMeasTypeIdx != 0;
  if(!bNotHrmUi) {
    [_ringMater setHrateVals:nHrate colIdx:nIdx];
  }
  _imgCaloryView.hidden = bNotHrmUi;
  _lblCaloryVal.hidden = bNotHrmUi;
  
  NSDate* dtMeas = [NSDate date];
  //dur
  double dDecDur = [dtMeas timeIntervalSinceDate:_dtLast];
  if(nIdx > 0 && _dtLast != nil) {
    _pfDurHrate[nIdx-1] += dDecDur;
  }
  //for(int i=0; i<_nDurtBarNumber; i++) {
    //_fPoints += _pfDurHrate[i] * _pfPointCoef[i] / 60;
  //}
  
  //burn calory
  _dtMeas = dtMeas;
  [self calDisplayBurnedVal:nHrate];
  
  //store
  if(nHrate > 0 && _nHrateId > 0)  {
    [pApp insertHrateItemData:_nHrateId bodyId:_nBodyId hRate:nHrate dtime:_dtMeas toSvr:YES];
  }
  
  double dElapsed = [dtMeas timeIntervalSinceDate:_dtHrmPoint];
  _lblHrateElaped.text = [pApp getHourMinSec:dElapsed];
  
  //avg hrate display
  double dTotalSecond = [dtMeas timeIntervalSinceDate:_dtHrmPoint];
  double dDurSeconds = dDecDur;
  dTotalSecond -= dDurSeconds;
  if(_dAvgHrate < 1)
    _dAvgHrate = nHrate;
  else
    _dAvgHrate = (_dAvgHrate * dTotalSecond + nHrate * dDurSeconds) / (dTotalSecond + dDurSeconds);
  if(_nMeasTypeIdx == 0)
    [_ringMater setHrtHrtAvgTips:(short)(_dAvgHrate+0.5)];
  
  _dtLast = dtMeas;
  _nHrmRcvCount++;
  
  pApp.m_nLastHrate = nHrate;
  pApp.m_nCurtAvgHrt = (short)(_dAvgHrate+0.5);
}

- (void) calDisplayBurnedVal:(short)nRate
{
  if(_dtMeas == nil)
    _dtMeas = [NSDate date];
  
  double dDurSeconds = [_dtMeas timeIntervalSinceDate:_dtLast];
  
  short nMaxHrt = 210 - _nAgeYear / 2 - _fBodyWgt * 0.05;
  if(_nSexNum == 1)
    nMaxHrt += 4;
  
  //cal calories
  CGFloat fCalories = [self calBurnedCalories:nRate second:dDurSeconds wgt:_fBodyWgt age:_nAgeYear sex:_nSexNum];
  _fCalry += fCalories * 1000.0;
  
  //NSString* sCalUnit = @"C";
  /*if(_fCalry < 0) {
    _fCalry = 0;
  }
  else if(_fCalry > 1000) {
    _fCalry /= 1000.0;
    //sCalUnit = @"k-C";
  }*/
  
  //local store
  /*if(nRate > 0)  {
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp insertHrateItemData:_nHrateId bodyId:_nBodyId hRate:nRate dtime:_dtMeas toSvr:YES];
  }*/
  
  if(!_lblCaloryVal.hidden)
    _lblCaloryVal.text = [NSString stringWithFormat:@"%.0f", _fCalry];
}

- (CGFloat) calBurnedCalories:(short) nHrate second:(double)dSec wgt:(double)dWgt age:(short)nAge sex:(short)nSex
{
  CGFloat fCalories = 0.0;
  if(nSex == 1) {
    fCalories = ((0.2017 * nAge + 0.1988 * dWgt + 0.6309 * nHrate - 55.0969) / 4.184) * (dSec / 60.0) / 1000.0;
  }
  else {
    fCalories = ((0.074 * nAge - 0.1263 * dWgt + 0.4472 * nHrate - 20.4022) / 4.184) * (dSec / 60.0) / 1000.0;
  }
  if(fCalories < 0)
    fCalories = 0;
  return fCalories;
  
}


- (void) recvedWiFiHexData:(UInt8*)pData len:(int)nLen
{
    if(nLen > 50)
        return;
    
    int nPos = nLen - 21;
    UInt8 *pHex = pData + nPos;
    pData[nPos-1] = 0x00;
    NSString* sMsg = [NSString stringWithCString:(char*)pData encoding:NSASCIIStringEncoding];
    NSArray *listItems = [sMsg componentsSeparatedByString:@" "];
    NSUInteger nCount = [listItems count];
    if(nCount< 2) {
        return;
    }
    NSString* sDevId = [listItems objectAtIndex:0];
    NSString* sTagId = [listItems objectAtIndex:1];
    
    short nIdx = 0;
    UInt8 nWgth = pHex[nIdx++];
    UInt8 nWgtl = pHex[nIdx++];
    UInt8 nWu = pHex[nIdx++];
    _nWgtUnit = nWu;
    
    float dWgt = ((nWgth << 8) + nWgtl) / 10.0;
    _bFixBleUser = NO;
    //[self showMeasInfo:dWgt];
    
    UInt8 nFath = pHex[nIdx++];
    UInt8 nFatl = pHex[nIdx++];
    float fFat = ((nFath << 8) + nFatl) / 10.0;
    
    UInt8 nWath = pHex[nIdx++];
    UInt8 nWatl = pHex[nIdx++];
    float fWat = ((nWath << 8) + nWatl) / 10.0;
    
    UInt8 nMush = pHex[nIdx++];
    UInt8 nMusl = pHex[nIdx++];
    //float fMus = ((nMush << 8) + nMusl) / 10.0;
    
    UInt8 nBmrh = pHex[nIdx++];
    UInt8 nBmrl = pHex[nIdx++];
    //float fBmr = ((nBmrh << 8) + nBmrl);
    
    UInt8 nBonh = pHex[nIdx++];
    UInt8 nBonl = pHex[nIdx++];
    float fBon = ((nBonh << 8) + nBonl) / 10.0;
    fBon = _KgtoLb;
    
    //UInt8 niFath = pHex[nIdx++];
    //UInt8 niFatl = pHex[nIdx++];
    //float fIfat = ((niFath << 8) + niFatl) / 10.0;
    
    UInt8 nYear = pHex[nIdx++];
    UInt8 nMon = pHex[nIdx++];
    UInt8 nDate = pHex[nIdx++];
    UInt8 nHour = pHex[nIdx++];
    UInt8 nMin = pHex[nIdx++];
    UInt8 nSec = pHex[nIdx];
    NSString* dtMeas = [NSString stringWithFormat:@"%i-%i-%i %i:%i:%i", 2000+nYear, nMon, nDate, nHour, nMin, nSec];
    
    float fRmr = 0;
    float fWgtKg = dWgt;
    if(_nWgtUnit != 1)
        fWgtKg *= _LbtoKg;
    if(_nSexNum == 0) { //female
        fRmr = 655 + (9.56 * fWgtKg) + (1.85 * _fBodyHgt) - (4.68 * _nAgeYear);
    }
    else {
        fRmr = 66.6 + (13.8 * fWgtKg) + (5.0 * _fBodyHgt) - (6.76 * _nAgeYear);
    }
    
    /*if(fFat > 0 && fWat > 0) {
        _fatWatView.hidden = NO;
        [_fatWatView updateView:fFat wat:fWa t isBle:_bConnBleScale];
    }
    if(fMus > 0 && fBmr > 0) {
        [_fatWatView updateOthView:fMus bmr:(short)fBmr bone:fBon iFat:fIfat];
    }
    _lblState.text = [NSString stringWithFormat:@"(%@) %@", sTagId, dtMeas];
    
    //store in local
    long long nOth = ((long long)niFath << 56) + ((long long)niFatl << 48) + ((long long)nBonh << 40) + ((long long)nBonl << 32) +
    ((long)nBmrh << 24) + ((long)nBmrl << 16) + ((long)nMush << 8) + nMusl;
    [self saveWgtFatData:dWgt unit:nWn fat:fFat wat:fWat oth:nOth hgt:_dLastBodyHgt isFat:YES send:NO];*/
    
    long long nOth =((long long)nBonh << 40) + ((long long)nBonl << 32) + ((long long)(nBmrh << 24)) + + ((long long)nBmrl << 16) + ((long long)nMush << 8) + nMusl;
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [self insWgtData:sDevId card:sTagId data:dWgt unit:nWu dtScale:dtMeas toSvr:NO];
    
    NSString* sInitDtFmt = pApp.dtFmt.dateFormat;
    [pApp insertFatData:pApp.m_bodyInfo.m_nBodyId fat:fFat wat:fWat hgt:_nHgtMm / 10 unit:1 oth:nOth date:[pApp.dtFmt dateFromString:dtMeas] toSvr:NO];
    
    [pApp CloseScaleHost];
    [pApp.dtFmt setDateFormat:sInitDtFmt];
    
    [self setLastWgtMeasData:dWgt unit:nWu fat:fFat wat:fWat];
    /*float fBmi = fWgtKg * 10000.0 / _nHgtCm / _nHgtCm;
    [_ringMater setMeasVals: dWgt fat:fFat];
    [_ivBottom setFatWatBmiVal:fFat wat:0.0 bmi:fBmi];*/
    
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
        AudioServicesPlaySystemSound(1115);
    else
        AudioServicesPlaySystemSound(1315);
}

//ble function
- (void) initWiFiBleDev
{
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  _NcitWiFiDev = appDelegate.m_ncitWiFiDev;
  _ncitBleDev = appDelegate.m_ncitBleDev;
  
  //_ncitBleDev.bleDelegate = nil;
  _ncitBleDev.bSyncDevData = NO;
  _ncitBleDev.nDevTypeIdx = _nMeasTypeIdx;
}


//interface send data to scale

- (void) sendDataToBleDev:(CBCharacteristic*)aChar
{
  //_lblMsg.text = @"Nuy Scale";
  uint8_t val[5] = {0x41, 0x43, 0x57, 0x55, 0xFF};
  val[4] = (uint8_t)(_nWgtUnit==1)?0: 1;
  
  //send wgt unit
  NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
  [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithResponse];
  
  _lblMsg.text = NSLocalizedString(@"Nuyu BLE Scale Ready!", nil);
}

- (void) sendDataToYunmaiBleDev:(CBCharacteristic*)aChar
{
  if(_nMeasTypeIdx != 3)
    return;
  
  uint8_t nChest = (uint8_t)((_nChestCm == 0)?0x5b:_nChestCm);
  uint8_t nWaist = (uint8_t)((_nChestCm == 0)?0x3e:_nWaistCm);
  
  uint8_t nWgtUnit = (uint8_t)_nWgtUnit;
  
  //uint8_t nSum = _CurtPerson;//0x03;
  //uint8_t val[15] = {0x0f, 0x90, 0x01, 0x01, 0x00, 0x00, 0x00, _nHgtCm, _nSexNum, _nAgeYear, 0x11, 0x22, 0x12, 0x23, 0x02};
  uint8_t val[15] = {0x0f, 0x90, 0x01, 0x01, 0x00, 0x00, 0x00, _nHgtMm/10, _nSexNum, _nAgeYear, nChest, nWaist, 0x19, 0x48, nWgtUnit};
  
  NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
  //[_peripheral writeValue:valData forCharacteristic:aChar type:CBCharacteristicWriteWithResponse];//CBCharacteristicWriteWithoutResponse];
  //[_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithResponse];
  if([_ncitBleDev sendBodyInfoToYunmaiDev:aChar data:valData type: CBCharacteristicWriteWithResponse])
    _lblMsg.text = NSLocalizedString(@"BLE Scale Ready", nil);
  [_ringMater setMeasVals:0.0 fat:0.0 un:_nWgtUnit];
}

//ble protocal
- (void) bleSupport:(BOOL)bSupport
{
    if(!bSupport) {
        _lblMsg.text = NSLocalizedString(@"BLE Support?", nil);
    }
    
}

- (void) bleDevConnected
{
    if(_nMeasTypeIdx == 2) {
        if(_bSyncStepData) {
            _bSyncStepEnd = NO;
            _nLastSyncSteps = 0;
            _fLastSyncCalors = 0.0;
            _syncTimer = [NSTimer scheduledTimerWithTimeInterval:15.00 target:self selector:@selector(onSyncTimer) userInfo:nil repeats:NO];
        }
        _bConnBleDev = YES;
        _cbdPedoDev.hidden = YES;
        _ncitBleDev.bleDelegate = self;
        UIImage* iBtn = [UIImage imageNamed:@"btn-stop.png"];
        [_btnPlay setBackgroundImage:iBtn forState:UIControlStateNormal];
    }
    else if(_nMeasTypeIdx == 0) {
      
    }
    //[self turnOnWiFiConn];
    _lblMsg.text = NSLocalizedString(@"BLE Device Connected", nil);//[NSString stringWithFormat: @"%@ %s", [aPeripheral name], "Connected"];
}

/*- (void) bleDevConnected:(NSString*)sUuid
{
    _nLastSyncIdx = 0;
    _nLastSyncSteps = 0;
    _fLastSyncCalors = 0.0;
    _syncTimer = [NSTimer scheduledTimerWithTimeInterval:9.00 target:self selector:@selector(onSyncTimer) userInfo:nil repeats:NO];
}*/

/********************/
/*   Step monitor   */
/********************/
-(void) onSyncTimer
{
    if(!_bSyncStepEnd) {
        //_bSyncException = YES;
        _lblMsg.text = NSLocalizedString(@"Time out! no stored date", nil);
        [_ncitBleDev stopMeas];
        
        UIImage* iBtn = [UIImage imageNamed:@"ic-play.png"];
        [_btnPlay setBackgroundImage:iBtn forState:UIControlStateNormal];
    }
    [_syncTimer invalidate];
}

- (void) scanStepMonitor
{
    [_ncitBleDev startMeas:nil];
    _ncitBleDev.bleDelegate = self;
}

- (uint8_t) getCheckSum:(uint8_t *)pVal len:(short)nLen
{
    uint8_t nSum = 0;
    for(short i=0; i<nLen; i++) {
        nSum += pVal[i];
    }
    return nSum;
}

- (void) sendUserDataToPedoDev:(uint8_t) d0 char:(CBCharacteristic*)aChar
{
    //_lblMsg.text = @"Init data";
    uint8_t nIdx = d0 >> 4;
    short nWgt = _fBodyWgt * 10;
    uint8_t nWgth = nWgt >> 8;
    uint8_t nWgtl = nWgt & 0xff;
    uint8_t nStep = _nHgtMm * 4.04;
    uint8_t val[12] = {0xe1, nIdx, nWgth, nWgtl, _nAgeYear, _nHgtMm / 10, nStep, _nSexNum, 0X00, 0x27, 0x10, 0x00};
    
    val[11] = [self getCheckSum:val len:11];
    
    NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
    [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
}

- (void) sendUtcDateTimeData:(uint8_t) d0 char:(CBCharacteristic*)aChar
{
    uint8_t nIdx = d0 >> 4;
    NSDate* dt = [NSDate date];
    /*NSTimeZone* locZone = [NSTimeZone systemTimeZone];
    NSInteger nInterval = [locZone secondsFromGMTForDate:dt];
    dt = [dt dateByAddingTimeInterval: nInterval];*/
    NSUInteger dtScds = (NSUInteger)[dt timeIntervalSince1970];
    uint8_t nUdch1 = (dtScds & 0xff000000) >> 24;
    uint8_t nUdch2 = (dtScds & 0x00ff0000) >> 16;
    uint8_t nUdch3 = (dtScds & 0x0000ff00) >> 8;
    uint8_t nUdch4 = (dtScds & 0x000000ff);
    
    uint8_t val[7] = {0xe2, nIdx, nUdch1, nUdch2, nUdch3, nUdch4, 0x00};
    val[6] = [self getCheckSum:val len:6];
    
    NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
    [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
}

- (void) syncDetailActData:(uint8_t) d0 char:(CBCharacteristic*)aChar
{
    uint8_t nIdx = d0 >> 4;
    
    uint8_t val[4] = {0xe0, nIdx, 0x00, 0x00};
    val[3] = [self getCheckSum:val len:3];
    
    NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
    [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
}

- (void) syncStpDetailData:(uint8_t) d0 data:(const uint8_t *)rcvData len:(NSUInteger)nDataLen char:(CBCharacteristic*)aChar
{
    uint8_t nIdx = d0 >> 4;
    
    if(_bSyncStepData && nDataLen == 15) { //sysn data
        //uint8_t nPackIdx = rcvData[1];
        //BOOL bNewSyncMeas = nPackIdx == 0x01;
        //int nStart = bNewSyncMeas?6:2;
        //_bNewSyncMeas = bNewSyncMeas;
        //BOOL bNeedInsNew = NO;
        NSUInteger nUtc = (rcvData[1] << 24) + (rcvData[2] << 16) + (rcvData[3] << 8) + rcvData[4];
        NSDate* dtMeas = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)nUtc];;
        /*if(bNewSyncMeas) {
            NSUInteger nUtc = (rcvData[1] << 24) + (rcvData[2] << 16) + (rcvData[3] << 8) + rcvData[4];
            dtMeas = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)nUtc];
            //NSTimeZone* locZone = [NSTimeZone systemTimeZone];
            //NSInteger nInterval = [locZone secondsFromGMTForDate:dtMeas];
            //dtMeas = [dtMeas dateByAddingTimeInterval: nInterval];
            
            if(_dtSyncStart != nil)
                bNeedInsNew = ![dtMeas isEqualToDate:_dtSyncStart];
            else
                bNeedInsNew = YES;
            
            _dtSyncStart = dtMeas;
        }*/
        
        /*if(dtMeas != nil && bNewSyncMeas && bNeedInsNew) {
            //if(_dtLastSync != nil)
                //[self endOneSyncData];
            
            //[self insertStartHRMData:dtMeas];
            _dtLastSync = dtMeas; 
        }
        
        _nLastSyncSteps = 0;
        _fLastSyncCalors = 0.0;
        AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        for(int i=nStart; i<nDataLen-2; i=i+2) {
            _nLastSyncSteps += bNewSyncMeas?rcvData[i]: rcvData[i+1];
            _fLastSyncCalors += bNewSyncMeas?rcvData[i+1]: rcvData[i];
            _dtLastSync = [_dtLastSync dateByAddingTimeInterval:2];
        }
        _nLastSyncIdx = nPackIdx;
        float fDists = pApp.m_fStepLength * _nLastSyncSteps;
        [pApp insertStepsData:0 bodyId:_nBodyId step:_nLastSyncSteps dist:fDists calory:_fLastSyncCalors date:_dtLastSync];*/
        
        AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        _nLastSyncSteps = (rcvData[5] >> 16) + (rcvData[6] >> 8) + rcvData[7];
        if(_nLastSyncSteps > 0) {
            int nDists = (rcvData[8] << 16) + (rcvData[9] << 8) + rcvData[10];
           _fLastSyncDists = nDists / 1000.0;
            _fLastSyncCalors = ((rcvData[11] << 16) + (rcvData[12] << 8) + rcvData[113]) / 10.0;
            [pApp insertStepsData:_nBodyId step:_nLastSyncSteps dist:_fLastSyncDists calory:_fLastSyncCalors date:dtMeas add:YES toSvr:NO];
            
            //show Sync stpes
            int nSteps = _nLastSyncSteps + _ringMater.sLastLabelTxt.intValue;
            [_ringMater setMeasIntVals:nSteps];
        
            _nSteps = 0;
            _lblMsg.text = [NSString stringWithFormat:NSLocalizedString(@"Sync steps data...", nil)]; //[NSString stringWithFormat:@"Data length:%ld", (long)nDataLen];
        }
    }
    
    if(nIdx == 0x05) {
        uint8_t val[4] = {0xe0, nIdx, 0x00, 0x00};
        val[3] = [self getCheckSum:val len:3];
        NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
        [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
    }
    else {
        [self returnDevOk:d0 char:aChar];
    }
}

- (void) syncSleepData:(uint8_t) d0 char:(CBCharacteristic*)aChar
{
    /*uint8_t nIdx = d0 >> 4;
    
    uint8_t val[4] = {0xe0, nIdx, 0x00, 0x00};
    val[3] = [self getCheckSum:val len:3];
    
    NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
    [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
    
    [NSThread sleepForTimeInterval:0.25];*/
    [self returnDevOk:(uint8_t) d0 char:aChar];
    
}

- (void) syncDeviceData:(uint8_t) d0 char:(CBCharacteristic*)aChar
{
    /*uint8_t nIdx = d0 >> 4;
    
    uint8_t val[4] = {0xe0, nIdx, 0x00, 0x00};
    val[3] = [self getCheckSum:val len:3];
    
    NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
    [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
    
    [NSThread sleepForTimeInterval:0.25];
    [_ncitBleDev disablePedoSyncSvr];*/
    
    [self returnDevOk:(uint8_t) d0 char:aChar];
}

- (void) syncCycleData:(uint8_t) d0 char:(CBCharacteristic*)aChar
{
    /*uint8_t nIdx = d0 >> 4;
    
    uint8_t val[4] = {0xe0, nIdx, 0x00, 0x00};
    val[3] = [self getCheckSum:val len:3];
    
    NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
    [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];*/
    [self returnDevOk:(uint8_t) d0 char:aChar];
}

- (void) returnDevOk:(uint8_t) d0 char:(CBCharacteristic*)aChar
{
    uint8_t nIdx = d0 >> 4;
    
    uint8_t val[4] = {0xe0, nIdx, 0x00, 0x00};
    val[3] = [self getCheckSum:val len:3];
    
    NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
    [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
}

- (void) showSyncMessage:(NSString*)sMsg
{
  _lblMsg.text = sMsg;
}

- (void) updateBatteryLevel:(short)nLevel
{
  [_ringMater updPedoBattery:nLevel];
  //NSString* sBatteryLevel = [NSString stringWithFormat:@"Battery level: %i", nLevel];
  //[self performSelectorInBackground:@selector(showSyncMessage:) withObject:sBatteryLevel];
}

- (void) recvedBleDevSyncData:(const uint8_t *)rcvData len:(NSUInteger)nDataLen char:(CBCharacteristic *)pChar
{
    if(_bSyncStepDataEnd)
        return;
    
    uint8_t d0 = rcvData[0];
    if(_ncitBleDev.bLoadSavedBleDev) {
        [self returnDevOk:d0 char:pChar];
        
        /*uint8_t val[6] = {0x06, 'd', 'o', 'n', 'e', 0x00};
        val[5] = [self getCheckSum:val len:5];
        NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
        [_ncitBleDev sendDataToBleDev:pChar data:valData type: CBCharacteristicWriteWithoutResponse];
        [_ncitBleDev enableSyncChar:pChar enable:NO];*/
        return;
    }
    /* uint8_t d2 = rcvData[2];
    uint8_t d3 = rcvData[3];
    uint8_t d4 = rcvData[4];
    
    uint8_t d5 = rcvData[5];
    uint8_t d6 = rcvData[6];
    uint8_t d7 = rcvData[7];
    uint8_t d8 = rcvData[8];
    uint8_t d9 = rcvData[9];
    
    uint8_t d10 = rcvData[10];
    uint8_t d11 = rcvData[11];
    uint8_t d12 = rcvData[12];
    uint8_t d13 = rcvData[13];
    uint8_t d14 = rcvData[14];
    
    uint8_t d15 = rcvData[15];
    uint8_t d16 = rcvData[16];*/
    //_lblMsg.text = [NSString stringWithFormat:@"data len: %i", (int)nDataLen];
    if((d0 & 0x0f) == 0x01) {
      [self performSelectorInBackground:@selector(showSyncMessage:) withObject:NSLocalizedString(@"Sending user info...", nil)];
      [self sendUserDataToPedoDev:d0 char:pChar];
      //_lblMsg.text = @"User Info sent";
    }
    else if((d0 & 0x0f) == 0x02) {
      [self performSelectorInBackground:@selector(showSyncMessage:) withObject:NSLocalizedString(@"UTC data sending...", nil)];
      [self sendUtcDateTimeData:d0 char:pChar];
      //_lblMsg.text = @"UTC data sent";
    }
    else if((d0 & 0x0f) == 0x03) {
        //_bSyncStepEnd = NO;
        /*if(_bSyncStepData)
            _lblMsg.text = @"Sync Steps Details Data";
        else
            _lblMsg.text = @"Pass over Sync Data!";
        [self syncStpDetailData:d0 data:rcvData len:nDataLen char:pChar];*/
      [self performSelectorInBackground:@selector(showSyncMessage:) withObject:NSLocalizedString(@"Just OK", nil)];
      [self returnDevOk: d0 char:pChar];
    }
    else if((d0 & 0x0f) == 0x04) {
        [self performSelectorInBackground:@selector(showSyncMessage:) withObject:NSLocalizedString(@"Details Data Recving...", nil)];
        [self syncDetailActData:d0 char:pChar];
    }
    else if((d0 & 0x0f) == 0x05) {
        [self performSelectorInBackground:@selector(showSyncMessage:) withObject:NSLocalizedString(@"Sleep data...(OK)", nil)];
        [self syncSleepData:d0 char:pChar];
         //_lblMsg.text = @"Sleep data synced";
    }
    else if((d0 & 0x0f) == 0x07) {
      [self performSelectorInBackground:@selector(showSyncMessage:) withObject:NSLocalizedString(@"Device inofo group...(OK)", nil)];
      [self syncDeviceData:d0 char:pChar];
      //_lblMsg.text = @"Device inofo group synced";
    }
    else if((d0 & 0x0f) == 0x09) {
      [self performSelectorInBackground:@selector(showSyncMessage:) withObject:NSLocalizedString(@"Cycle data...(OK)", nil)];
      [self syncCycleData:d0 char:pChar];
      //_lblMsg.text = @"Cycle data synced";
    }
    else if((d0 & 0x0f) == 0x06) {
      _pBlePedoChar = pChar;
      [self returnDevOk:d0 char:pChar];
        //_lblMsg.text = @"Completed!";
      _bSyncStepDataEnd = YES;
      [_ncitBleDev enableSyncChar:_ncitBleDev.pBleDevChar enable:NO];
      [self performSelectorInBackground:@selector(showSyncMessage:) withObject:NSLocalizedString(@"Completed", nil)];
      [_ncitBleDev enablePedoDevMeas];
    }
}

- (void) recvedBlePedoStepData:(const uint8_t *)rcvData len: (NSUInteger)nDataLen
{
    if(_bSyncStepData || !_bSyncStepDataEnd)
       return;
   
  /*if(_pBlePedoChar) {
    if((rcvData[0] & 0x0f) != 0x03)
      [self returnDevOk:rcvData[0] char:_pBlePedoChar];
  }*/
       
  int nSteps = (rcvData[2] << 16) + (rcvData[3] << 8) + rcvData[4];
  int nDists = (rcvData[5] << 16) + (rcvData[6] << 8) + rcvData[7];
  float fDists = nDists / 1000.0;
  float fCalors = ((rcvData[8] << 16) + (rcvData[9] << 8) + rcvData[10]) / 10.0;
  NSString* sInfo = [NSString stringWithFormat:@"Steps: %i, Dists: %.1f mi, Cal: %.1f k-Cal", nSteps, fDists, fCalors];
    
  if(nSteps >= 0) {
    [UIView animateWithDuration:0.5 animations:^{
      _lblMsg.alpha = 0.0f;
      _lblMsg.text = sInfo;
      _lblMsg.alpha = 1.0f;
    }];
        
    _nSteps = nSteps;
    _fDists = fDists;
    _fCalors = fCalors;
        
    [_ringMater setMeasIntVals:nSteps];
    [self setLastStepMeasData:nSteps];
      
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp sendWfbsDataToSvr:_nBodyId measId:0 sn:@"" wgt:0.0 wu:0 measTime:[NSDate date]
                        fat:0.0 wat:0.0 hgt:0.0 hu:0 oth:0
                        bph:0 bpl:0 hrt:0
                        stp:nSteps dist:fDists calory:fCalors type:255];
  }
}

/**********************/
/*   bleWgt monitor   */
/**********************/
- (double) getVdrBleLbWgtVal:(short)nWgtVal
{
  int nWgtLb = (int)((nWgtVal * 0x2B0F / 0xC350 + 1) / 2) * 2;
  double dWgtLb = nWgtLb / 10.0;
  if(dWgtLb > 210)
    return dWgtLb + 0.025;
  else if((dWgtLb > 180))
    return dWgtLb - 0.005;
  else if((dWgtLb > 150))
    return dWgtLb - 0.045;
  else
    return dWgtLb + 0.055;
}

- (void) recvedBleWgtData:(double)dWgt fat:(float)fFat wat:(float)fWat mus:(float)fMus bone:(float)fBone wUnit:(short)nWu fatwatInc:(BOOL)bFatWat hgt:(float)fHgt
{
  [_ncitBleDev stopMeas];
  if(nWu == 0) {
    nWu = _nWgtUnit;
    if(_nWgtUnit == 2) {
      dWgt *= _KgtoLb;
    }
  }
  
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
  NSString* sTime = [pApp.dtFmt stringFromDate:[NSDate date]];
  [self insWgtData:@"BleScale" card:@"0" data:dWgt unit:nWu dtScale:sTime toSvr:YES];
  [pApp insertFatData:pApp.m_bodyInfo.m_nBodyId fat:fFat wat:fWat hgt:fHgt unit:1 oth:0 date:[NSDate date] toSvr:YES];
  
  //[pApp CloseScaleHost];
  [self setLastWgtMeasData:dWgt unit:nWu fat:fFat wat:fWat];
  
  if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
    AudioServicesPlaySystemSound(1115);
  else
    AudioServicesPlaySystemSound(1315);
  
  [_ncitBleDev setConnBleName:nil];
}

- (void) recvedVdrBleWgtData:(double)dWgt fat:(float)fFat wat:(float)fWat mus:(float)fMus bone:(float)fBone wUnit:(short)nWu fatwatInc:(BOOL)bFatWat hgt:(float)fHgt wgt:(short)nWgt
{
  [_ncitBleDev stopMeas];
  if(nWu == 0) {
    nWu = _nWgtUnit;
    if(_nWgtUnit == 2) {
      //dWgt = [self getVdrBleLbWgtVal:nWgt];
      dWgt *= _KgtoLb;
    }
  }
  
  
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
  NSString* sTime = [pApp.dtFmt stringFromDate:[NSDate date]];
  [self insWgtData:@"VdrBleScale" card:@"0" data:dWgt unit:nWu dtScale:sTime toSvr:YES];
  if(fFat > 0)
    [pApp insertFatData:pApp.m_bodyInfo.m_nBodyId fat:fFat wat:fWat hgt:fHgt unit:1 oth:0 date:[NSDate date] toSvr:YES];
  
  [self setLastWgtMeasData:dWgt unit:nWu fat:fFat wat:fWat];
  
  if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
    AudioServicesPlaySystemSound(1115);
  else
    AudioServicesPlaySystemSound(1315);
  
  [_ncitBleDev setConnBleName:nil];
  
}

- (void) bleDisconnected
{
  //_ncitBleDev.bleDelegate = nil;
  if(_nMeasTypeIdx == 0) {
    [self ProcrHrmStopMeas];
    UIImage* iBtn = [UIImage imageNamed:@"btn-search.png"];
    _lblPlayTips.text = NSLocalizedString(@"Find HRM", nil);
    [_btnPlay setBackgroundImage:iBtn forState:UIControlStateNormal];
  }
  else if(_nMeasTypeIdx == 2) {
    _bConnBleDev = NO;
    UIImage* iBtn = [UIImage imageNamed:@"ic-play.png"];
    [_btnPlay setBackgroundImage:iBtn forState:UIControlStateNormal];
  }
  
  if(_bSyncStepData || _nMeasTypeIdx == 2) {
    _bSyncStepEnd = YES;
    [self setLastStepMeasData:0];
    _lblMsg.text = _bSyncStepDataEnd?NSLocalizedString(@"Sync Data Completed!", nil):@"Stop!";
    if(_bSyncStepDataEnd)
      [_ncitBleDev loadSavedDevice:2];
  }
  else {
    [_ncitBleDev stopScan];
    [_ncitBleDev stopMeas];
    //_lblMsg.text = NSLocalizedString(@"BLE Disconnected!", nil);
  }
}

-(BOOL) storeRateRngData:(BOOL)bToSvr
{
  if(_nBodyId == 0 || _nHrateId == 0)
    return NO;
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  //NSDateFormatter* dtFmt = pApp.dtFmt;
  NSMutableArray* rateDate = [NSMutableArray arrayWithArray:[pApp loadHrateItemData:_nHrateId last:NO]];
  if(rateDate == nil || rateDate.count == 0)
    return NO;
  
  short nRngLow = (short)(_fRngLow + 0.5);
  short nRngUpp = (short)(_fRngUpp + 0.5);
  
  //NSDate* dtLast = [NSdate date];
  float fLowMinuts = 0, fMidMinuts=0, fHgtMinuts = 0;
  float fCalLow = 0, fCalMid = 0, fCalHgt = 0;
  short nLastIdx = 0;
  
  float fCalories = 0.0;
  NSUInteger nCount = rateDate.count;
  if(nCount > 0) {
    H_RateItem* hrItem = (H_RateItem*)[rateDate objectAtIndex:0];
    _dtLast = hrItem.hRateTime;
    short nHrate = [hrItem.hRateValue shortValue];
    fCalories = [self calBurnedCalories:nHrate second:2.0 wgt:_fBodyWgt age:_nAgeYear sex:_nSexNum];
  }
  //int nNum = 0;
  for(NSUInteger i=1; i<nCount; i++) {
    //nNum++;
    if(_dtLast == nil)
      continue;
    
    double dDurSeconds = 0;
    H_RateItem* hrItem = (H_RateItem*)[rateDate objectAtIndex:i];
    short nRate = [hrItem.hRateValue shortValue];
    if(nRate < nRngLow) {
      nLastIdx = 1;
    }
    else if((nRate >= nRngLow) && (nRate <= nRngUpp)) {
      nLastIdx = 2;
    }
    else {
      nLastIdx = 3;
    }
    
    NSDate* dt = hrItem.hRateTime;
    if(_dtLast != nil) {
      dDurSeconds = [dt timeIntervalSinceDate:_dtLast];
      if(dDurSeconds < 0)
        dDurSeconds = 2;
      
      if(nLastIdx == 1)
        fLowMinuts += dDurSeconds;
      else if(nLastIdx == 2)
        fMidMinuts += dDurSeconds;
      else if(nLastIdx == 3)
        fHgtMinuts += dDurSeconds;
    }
    
    
    //calories burned
    
    fCalories += [self calBurnedCalories:nRate second:dDurSeconds wgt:_fBodyWgt age:_nAgeYear sex:_nSexNum];
    
    if(nLastIdx == 1)
      fCalLow += fCalories;
    else if(nLastIdx == 2)
      fCalMid += fCalories;
    else if(nLastIdx == 3)
      fCalHgt += fCalories;
    
    
    fCalories = 0;
    _dtLast = dt;//[_dtLast dateByAddingTimeInterval:dDurSeconds];
  }
  //_lblHrateVal.text = [NSString stringWithFormat:@"%.0f C", (fCalLow + fCalMid + fCalHgt) * 1000];
  
  if(fCalLow < 0)
    fCalLow = 0.0;
  if(fCalMid < 0)
    fCalMid = 0.0;
  if(fCalHgt < 0)
    fCalHgt = 0.0;
  
  NSDate* dtMeas = _dtHrmPoint;//
  fLowMinuts /= 60.0;
  fMidMinuts /= 60.0;
  fHgtMinuts /= 60.0;
  
  //local store
  //NSInteger nId = 0;
  //low rate
  NSString* sRateRngText = [NSString stringWithFormat:@"< %d bpm", nRngLow];
  if(fLowMinuts >= 0.0001)
    [pApp insertHrateRngData:_nHrateId bodyId:_nBodyId idx:1 rng:sRateRngText dur:fLowMinuts cal:fCalLow dtVal:dtMeas toSvr:bToSvr];
  //mid rate
  if( fMidMinuts >= 0.0001) {
    sRateRngText = [NSString stringWithFormat:@"%d ~ %d bpm", nRngLow, nRngUpp];
    [pApp insertHrateRngData:_nHrateId bodyId:_nBodyId idx:2 rng:sRateRngText dur:fMidMinuts cal:fCalMid dtVal:dtMeas toSvr:bToSvr];
  }
  //mid rate
  if(fHgtMinuts >= 0.0001) {
    sRateRngText = [NSString stringWithFormat:@"> %d bpm", nRngUpp];
    [pApp insertHrateRngData:_nHrateId bodyId:_nBodyId idx:3 rng:sRateRngText dur:fHgtMinuts cal:fCalHgt dtVal:dtMeas toSvr:bToSvr];
  }
  
  _nHrateId = 0;
  
  return YES;
}

- (void) bleUserClosed
{
  _ncitBleDev.bleDelegate = nil;
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  _lblMsg.text = (pApp.m_bSupportBle)? NSLocalizedString(@"BLE Disconnected!", nil): @"BLE Closed, Session Ended";
  
  if(_pHrate != nil) {
    [pApp updHrateStartEndTime:_pHrate startTime: nil endTime:[NSDate date] toSvr:YES];
    [self storeRateRngData:YES];
    pApp.m_nHrateId = 0;
    _pHrate = nil;
  }
  AudioServicesPlaySystemSound(1112);
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
  BOOL isInside = YES;
  UITouch *touch = [touches anyObject];
  
  if(_ddlUserList != nil && _ddlUserList.isPopup) {
    CGPoint pt =[touch locationInView:_ddlUserList];
    isInside = [_ddlUserList pointInside:pt withEvent:event];
    if(!isInside) {
      [_ddlUserList hideDropDownList];
      _lblMsg.text = NSLocalizedString(@"Cancel", nil);
    }
  }
  
  [_ringMater hideKeyboard];
  if(_wifiScaleTimer != nil) {
    [_wifiScaleTimer invalidate];
    _wifiScaleTimer = nil;
  }
  
  if(_wmtWgtType == nil && _cbdPedoDev == nil)
    return;
  if(_wmtWgtType.hidden && _cbdPedoDev.hidden)
    return;
  
  //if(!_wmtWgtType.hidden) {
    //_wmtWgtType.hidden = YES;
  //}
    
  if(_wmtWgtType != nil && !_wmtWgtType.hidden) {
    CGPoint pt =[touch locationInView:_wmtWgtType];
    isInside = [_wmtWgtType pointInside:pt withEvent:event];
    if(!isInside) {
      [self stopWgtTypeCtrl];
      [_ringMater setManualMode:NO];
      _lblMsg.text = NSLocalizedString(@"Cancel", nil);
      return;
    }
  }
    
  //CGPoint touchPointInButton = [touch locationInView:_cbdPedoDev];
  if(_cbdPedoDev != nil && !_cbdPedoDev.hidden) {
    CGPoint pt =[touch locationInView:_cbdPedoDev];
    isInside = [_cbdPedoDev pointInside:pt withEvent:event];
    if(!isInside) {
      [_cbdPedoDev close];
      //[_cbdPedoDev removeFromSuperview];
      _cbdPedoDev.hidden = YES;
      _lblMsg.text = NSLocalizedString(@"Cancel", nil);
      //_cbdPedoDev = nil;
      return;
    }
  }
}

- (void) stopWgtTypeCtrl
{
    if(_wmtWgtType != nil) {
        [_wmtWgtType rmvWgtTypeButs];
        _wmtWgtType.wtDelegate = nil;
        [_wmtWgtType removeFromSuperview];
        _wmtWgtType = nil;
    }
}

#pragma mark Core Date insert operation
- (BOOL) insWgtData:(NSString*)sSn card:(NSString*)cn data:(float)fData unit:(short)iUnit dtScale:(NSString*) sTime toSvr:(BOOL)bToSvr
{
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  Boolean biOsTime = YES;//[sn hasPrefix:@"RIS"];
  NSInteger nBodyId = _nBodyId; //pApp.m_nBodyId;
  
  return [pApp insertWgtData:sSn card:cn data:fData unit:iUnit bodyId:nBodyId dtScale:sTime iOStime: biOsTime toSvr:bToSvr] != NULL;
    //return YES;
}

#pragma RingMeter text delete
- (void) CompleteTextInput
{
    _lblMsg.text = NSLocalizedString(@"Successfull Saved!", nil);
    //if(_nMeasTypeIdx == 3) {
        //[self setLastWgtMeasData:0.0 unit:0.0 fat:0.0 wat:0.0];
    //}
}

- (void) updateGoalData
{
  if(_nMeasTypeIdx == 3) {
    [self setLastWgtMeasData:0.0f unit:0 fat:0.0f wat:0.0f];
    _bUpdedWgtInfo = YES;
  }
}

- (void) updateLabelTips:(NSString*)sMsg
{
  _lblMsg.text = sMsg;
}

@end
